connector.rs 984 B

12345678910111213141516171819202122232425262728293031323334
  1. use futures::FutureExt;
  2. use smol::Async;
  3. use std::net::{SocketAddr, TcpStream};
  4. use crate::{
  5. error::{Error, Result},
  6. net::{Channel, ChannelPtr, SettingsPtr},
  7. util::sleep,
  8. };
  9. /// Create outbound socket connections.
  10. pub struct Connector {
  11. settings: SettingsPtr,
  12. }
  13. impl Connector {
  14. /// Create a new connector with default network settings.
  15. pub fn new(settings: SettingsPtr) -> Self {
  16. Self { settings }
  17. }
  18. /// Establish an outbound connection.
  19. pub async fn connect(&self, hostaddr: SocketAddr) -> Result<ChannelPtr> {
  20. futures::select! {
  21. stream_result = Async::<TcpStream>::connect(hostaddr).fuse() => {
  22. match stream_result {
  23. Ok(stream) => Ok(Channel::new(stream, hostaddr).await),
  24. Err(_) => Err(Error::ConnectFailed)
  25. }
  26. }
  27. _ = sleep(self.settings.connect_timeout_seconds).fuse() => Err(Error::ConnectTimeout)
  28. }
  29. }
  30. }