aboutsummaryrefslogtreecommitdiff
path: root/src/websocket.rs
blob: 19038ff699087ecc93329a686c24af2ba7e2f284 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use tungstenite::accept;
use std::net;
use super::*;

// Setup a new listener for websockets
// Iterate through them and create a new worker for each
pub fn websocket(db: Arc<Mutex<database::Database>>) {
    let listen = std::net::TcpListener::bind("127.0.0.1:8001").unwrap();

    loop {
        for connection in listen.incoming() {

            let wsconnectiondb = Arc::clone(&db);
            std::thread::spawn(move || {
                worker(wsconnectiondb, connection.unwrap())
            });
        }
    }
}

// Accept the connection and send a message to the client
// if a new message has been recieved by the server
fn worker(db: Arc<Mutex<database::Database>>, connection: net::TcpStream) {
    let mut websocket = accept(connection).unwrap();
    let mut newest = 0;

    // Main worker loop
    loop {
        // TX

        // Get the newest message id
        let mut db = db.lock().unwrap();
        let local_newest = match db.get_message_newest_id() {
            Some(n) => n.into(),
            None => 0
        };
        drop(db);

        // If there is a newer message then send a message to the client
        // and update the newest message
        if local_newest > newest {
            let m = serde_json::to_string(&WebSocketMessage::NewMessage).unwrap();

            // Close the client connection if we cannot send a message
            match websocket.write_message(tungstenite::Message::text(m)) {
                Ok(_) => (),
                Err(_) => break,
            };
            newest = local_newest;
        }

        // Sleep for 100ms to prevent cpu usage
        std::thread::sleep(std::time::Duration::from_millis(100));

        // RX
    //     let _ = match websocket.read_message() {
    //         Ok(n) => n,
    //         Err(_) => {println!("closed"); break}
    //     };

    //     // If the message is binary and contains a two byte header
    //     // then convert that header into a function call
    //     // and the rest of the message into json
    //     if msg.is_binary() {
    //         if msg.len() > 1 {
    //             match msg.into_data()[0..=1].into() {
    //                 BinaryMessage::GetMessageNewestId => {
    //                     let db = wsconnectiondb.lock().unwrap();
    //                     let m = db.get_message_newest_id();
    //                     drop(db);

    //                     let m = serde_json::to_string(&m).unwrap();
    //                     websocket.write_message(tungstenite::Message::text(m)).unwrap();
    //                 },
    //                 // Return error of unsupported data
    //                 _ => (),
    //             }

    //         // Return error of empty data
    //         } else {
    //             websocket.write_message(msg).unwrap();
    //         }

    //     // Otherwise if the message is text then print the text
    //     } else if msg.is_text() {
    //         println!("{}", msg.into_text().unwrap());
    //     }

    }

}