connector.rs 1.1 KB

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