time_protocol/
time_server.rs

1use core::time;
2use std::{
3    io::{self, Error, Read, Write},
4    net::{TcpListener, TcpStream},
5    thread,
6};
7
8use chrono::{NaiveDate, Utc};
9
10use crate::tool::i32_to_u8;
11
12lazy_static! {
13    // 1900和1970之间的timestamp差值
14    static ref DIFF: i64 = NaiveDate::from_ymd(1900, 1, 1)
15        .and_hms(0, 0, 0)
16        .timestamp()
17        .abs();
18}
19
20pub struct Server {
21    address: String,
22    port: u32,
23}
24
25impl Default for Server {
26    fn default() -> Self {
27        Self {
28            address: "127.0.0.1".to_string(),
29            port: 37,
30        }
31    }
32}
33
34impl Server {
35    pub fn new(address: &str, port: u32) -> Self {
36        Self {
37            address: address.to_string(),
38            port,
39        }
40    }
41
42    fn get_cur_time() -> i32 {
43        let ts = Utc::now().timestamp();
44
45        let time_since_1900 = ts + *DIFF;
46
47        let time = (time_since_1900 & 0x00000000FFFFFFFF) as i32;
48        time
49    }
50
51    fn handle_client(mut stream: TcpStream) -> io::Result<()> {
52        let mut buffer = [0; 512];
53        stream.read(&mut buffer).unwrap();
54
55        let response = Self::get_cur_time();
56        stream.write(&i32_to_u8(response))?;
57        stream.flush().unwrap();
58        thread::sleep(time::Duration::from_secs(1));
59        Ok(())
60    }
61
62    pub fn start(&self) -> Result<(), Error> {
63        let listener = TcpListener::bind(format!("{}:{}", self.address, self.port)).unwrap();
64        let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();
65
66        for stream in listener.incoming() {
67            let stream = stream.expect("failed");
68            let handle = thread::spawn(move || {
69                Self::handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error))
70            });
71            thread_vec.push(handle);
72        }
73
74        for handle in thread_vec {
75            handle.join().unwrap();
76        }
77        Ok(())
78    }
79
80    pub fn set_address(&mut self, address: &str) {
81        self.address = address.to_string();
82    }
83
84    pub fn set_port(&mut self, port: u32) {
85        self.port = port;
86    }
87}