connector.rs 1.0 KB

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