aboutsummaryrefslogtreecommitdiff
path: root/src/websocket.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/websocket.rs')
-rw-r--r--src/websocket.rs91
1 files changed, 91 insertions, 0 deletions
diff --git a/src/websocket.rs b/src/websocket.rs
new file mode 100644
index 0000000..19038ff
--- /dev/null
+++ b/src/websocket.rs
@@ -0,0 +1,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());
+ // }
+
+ }
+
+} \ No newline at end of file