connector.rs 1.0 KB

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