connector.rs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. use async_std::future::timeout;
  2. use std::time::Duration;
  3. use url::Url;
  4. use crate::{Error, Result};
  5. use super::{Channel, ChannelPtr, SettingsPtr, Transport};
  6. /// Create outbound socket connections.
  7. pub struct Connector {
  8. settings: SettingsPtr,
  9. }
  10. impl Connector {
  11. /// Create a new connector with default network settings.
  12. pub fn new(settings: SettingsPtr) -> Self {
  13. Self { settings }
  14. }
  15. /// Establish an outbound connection.
  16. pub async fn connect<T: Transport>(&self, hostaddr: Url) -> Result<ChannelPtr<T>> {
  17. let stream_result =
  18. timeout(Duration::from_secs(self.settings.connect_timeout_seconds.into()), async {
  19. let transport = T::new(None, 1024);
  20. let connect_stream = transport.dial(hostaddr.clone()).unwrap().await.unwrap();
  21. let channel = Channel::<T>::new(connect_stream, hostaddr).await;
  22. Ok(channel)
  23. })
  24. .await;
  25. match stream_result {
  26. Ok(t) => t,
  27. Err(_) => Err(Error::ConnectTimeout),
  28. }
  29. }
  30. }