file_transfer_system/
client.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use std::{error::Error, path::Path, time::Duration};

use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::TcpStream, time};
use bincode;
use crate::{file_transfer::PathType, network::Request};

pub struct Client {
    server_address: String,
    timeout: Option<Duration>,
    connection: Option<TcpStream>,  
}

impl Client {
    pub fn new(server_address: &str) -> Self {
        Self {
            server_address: server_address.to_string(),
            timeout: None,
            connection: None
        }
    }

    /// Sets a timeout duration for the client.
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = Some(timeout);
    }

    /// Connects to the server.
    pub async fn connect(&mut self) -> Result<(), Box<dyn Error>> {
        let timeout_duration = self.timeout.unwrap_or(Duration::from_secs(30)); // Default timeout
        let connect_future = TcpStream::connect(&self.server_address);

        // Apply timeout to the connection attempt
        let stream = time::timeout(timeout_duration, connect_future).await??;
        self.connection = Some(stream);
        Ok(())
    }

    /// Sends a request to the server.
    pub async fn send_request(&mut self, path: &Path) -> Result<(), Box<dyn Error>> {
        let path_type = match path.is_dir() {true => PathType::Directory, false => PathType::File};
        if let Some(ref mut connection) = self.connection {
            let request_bytes = bincode::serialize(&Request::Upload(path_type))?;
            let timeout_duration = self.timeout.unwrap_or(Duration::from_secs(30)); // Default timeout
            
            // Apply timeout to the write operation
            time::timeout(timeout_duration, connection.write_all(&request_bytes)).await??;
        } else {
            return Err("No active connection".into());
        }
        Ok(())
    }

    /// Reads a response from the server.
    pub async fn read_response(&mut self) -> Result<(), Box<dyn Error>> {
        if let Some(ref mut connection) = self.connection {
            let mut buffer = [0; 1024];
            let timeout_duration = self.timeout.unwrap_or(Duration::from_secs(30)); // Default timeout
            
            // Apply timeout to the read operation
            let bytes_read = time::timeout(timeout_duration, connection.read(&mut buffer)).await??;
            let response = bincode::deserialize(&buffer[..bytes_read])?;
            Ok(response)
        }
         else {
            Err("No active connection".into())
        }
    }

    /// Closes the connection to the server.
    pub async fn close(&mut self) -> Result<(), Box<dyn Error>> {
        if let Some(mut connection) = self.connection.take() {
            connection.shutdown().await?;
        }
        Ok(())
    }
}