Skip to main content

rusty_tracks/connection/
client.rs

1use std::net::{SocketAddr, TcpListener, TcpStream};
2use std::str::FromStr;
3use std::time::Duration;
4use crate::connection::Connection;
5
6pub struct Client{
7    host: String,
8    port: u16,
9}
10
11
12impl Client {
13    pub fn new(host: &str, port: u16) -> Self {
14        Client{ host: host.to_string(), port}
15    }
16
17    pub fn connect_timeout(&self, duration: Duration) -> Result<Connection, String> {
18        let addr = SocketAddr::from_str(&format!("{}:{}", self.host.clone(), self.port)).map_err(|_| "Invalid address".to_string())?;
19        let stream = TcpStream::connect_timeout(&addr, duration).unwrap();
20        Connection::new(&self.host, self.port, stream)
21    }
22
23    pub fn connect(&self) -> Result<Connection, String> {
24        let stream = TcpStream::connect((self.host.clone(), self.port)).unwrap();
25        Connection::new(&self.host, self.port, stream)
26    }
27
28}
29