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>) { 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>, 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()); // } } }