ping_client/
ping_client.rs

1//! Client side of script
2use easy_sockets::{
3    error::{deserialize_error, serialize_error, ErrorCode},
4    logger::log_error,
5    sleep,
6    sockets::tcp::{start_client, ClientTCP},
7    Deserialize, Duration, Serialize,
8};
9
10/// Error codes for server client connection
11enum PingError {
12    BadRequest,
13    InternalServerError,
14}
15impl ErrorCode for PingError {
16    fn to_code(&self) -> u16 {
17        match self {
18            PingError::BadRequest => 400,
19            PingError::InternalServerError => 500,
20        }
21    }
22
23    fn from_code(code: u16) -> Option<Self> {
24        Some(match code {
25            400 => PingError::BadRequest,
26            500 => PingError::InternalServerError,
27            _ => return None,
28        })
29    }
30
31    fn message(&self) -> &'static str {
32        match self {
33            PingError::BadRequest => "Request provided was invalid.",
34            PingError::InternalServerError => "Server encountered unexpected internal error.",
35        }
36    }
37}
38
39/// Message that a Client sends
40#[derive(Serialize, Deserialize)]
41enum ClientMsg {
42    Ping(String),
43}
44
45/// Message that the server sends
46#[derive(Serialize, Deserialize)]
47enum ServerMsg {
48    #[serde(
49        serialize_with = "serialize_error",
50        deserialize_with = "deserialize_error"
51    )]
52    Error(PingError),
53    Ping(String),
54}
55
56/// Client side
57struct Client {
58    ping_count: usize,
59}
60impl Client {
61    pub fn new() -> Self {
62        Self { ping_count: 0 }
63    }
64}
65impl ClientTCP for Client {
66    type ClientMsg = ClientMsg;
67    type ServerMsg = ServerMsg;
68
69    fn update(&mut self) -> Option<()> {
70        self.send_message(ClientMsg::Ping("Hello Server".into()))
71            .expect("Failed to send message");
72        sleep(Duration::from_secs(1));
73        // If you return None, client shuts down.
74        Some(())
75    }
76
77    fn handle_response(&mut self, response: Self::ServerMsg) {
78        match response {
79            ServerMsg::Error(error) => log_error(error),
80            ServerMsg::Ping(msg) => {
81                println!("Ping Received From Server: {}", msg);
82                self.ping_count += 1;
83            }
84        }
85    }
86}
87
88fn main() {
89    start_client("127.0.0.1:8000", Client::new()).expect("Failed to open client");
90}