time_protocol/
time_client.rs

1use crate::tool::u8_to_i32;
2use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, Utc};
3use std::io::{BufReader, Error, Read, Write};
4use std::net::TcpStream;
5
6lazy_static! {
7    // 1900和1970之间的timestamp差值
8    static ref DIFF: i64 = NaiveDate::from_ymd(1900, 1, 1)
9        .and_hms(0, 0, 0)
10        .timestamp()
11        .abs();
12
13    // 将格林尼治时间+8:00转化为中国时间
14    static ref CN_TIMEZONE:FixedOffset =FixedOffset::east(8 * 3600);
15}
16
17#[derive(Debug)]
18pub struct Client {
19    address: String,
20    port: u32,
21}
22
23impl Default for Client {
24    fn default() -> Self {
25        Client {
26            address: "127.0.0.1".to_string(),
27            port: 37,
28        }
29    }
30}
31
32impl Client {
33    pub fn new(address: &str, port: u32) -> Self {
34        Client {
35            address: address.to_string(),
36            port,
37        }
38    }
39
40    pub fn update(&self) -> Result<String, Error> {
41        let mut stream = TcpStream::connect(format!("{}:{}", self.address, self.port))?;
42
43        stream
44            .write("Getting timestamp".as_bytes())
45            .expect("Failed to write");
46
47        let mut reader = BufReader::new(&stream);
48        let mut buffer: [u8; 4] = [0; 4];
49
50        reader.read(&mut buffer)?;
51
52        let time = u8_to_i32(buffer);
53
54        let from_epoch = (time as i64 & 0xFFFFFFFF as i64) - *DIFF;
55
56        let dt = NaiveDateTime::from_timestamp(from_epoch, 0);
57
58        let now = DateTime::<Utc>::from_utc(dt, Utc).with_timezone(&*CN_TIMEZONE);
59        // format!("CurrentTime: {}", now);
60        Ok(format!("CurrentTime: {}", now))
61    }
62
63    pub fn set_address(&mut self, address: &str) {
64        self.address = address.to_string();
65    }
66
67    pub fn set_port(&mut self, port: u32) {
68        self.port = port;
69    }
70}