2025-11-11 13:35:34 +01:00
|
|
|
use futures_util::{SinkExt, StreamExt};
|
|
|
|
|
use serde::{Deserialize, Serialize};
|
2025-11-12 11:28:14 +01:00
|
|
|
use std::collections::HashMap;
|
|
|
|
|
use std::sync::Arc;
|
2025-11-11 13:35:34 +01:00
|
|
|
use tokio::net::TcpListener;
|
2025-11-12 11:28:14 +01:00
|
|
|
use tokio::sync::Mutex;
|
|
|
|
|
use tokio_tungstenite::accept_async;
|
|
|
|
|
use uuid::Uuid;
|
|
|
|
|
|
2025-11-12 12:49:42 +01:00
|
|
|
mod broadcast_message;
|
2025-11-12 11:28:14 +01:00
|
|
|
mod handle_connection;
|
2025-11-12 14:01:13 +01:00
|
|
|
mod server_event;
|
2025-11-11 13:35:34 +01:00
|
|
|
|
2025-11-12 12:49:42 +01:00
|
|
|
use handle_connection::handle_connection;
|
|
|
|
|
|
2025-11-11 13:35:34 +01:00
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
2025-11-12 11:28:14 +01:00
|
|
|
struct MessageData {
|
2025-11-11 13:35:34 +01:00
|
|
|
username: String,
|
2025-11-12 11:28:14 +01:00
|
|
|
userid: u32,
|
2025-11-11 13:35:34 +01:00
|
|
|
text: String,
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-12 11:28:14 +01:00
|
|
|
type Tx = futures_util::stream::SplitSink<
|
|
|
|
|
tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>,
|
|
|
|
|
tokio_tungstenite::tungstenite::Message,
|
|
|
|
|
>;
|
|
|
|
|
|
|
|
|
|
type ConnectionMap = Arc<Mutex<HashMap<Uuid, Tx>>>;
|
|
|
|
|
|
2025-11-11 13:35:34 +01:00
|
|
|
#[tokio::main]
|
|
|
|
|
async fn main() {
|
2025-11-12 11:28:14 +01:00
|
|
|
let address = "0.0.0.0:9001"; //address to connect to
|
2025-11-11 13:35:34 +01:00
|
|
|
let listener = TcpListener::bind(address).await.unwrap();
|
|
|
|
|
println!("Server running on ws://{}", address);
|
|
|
|
|
|
2025-11-12 11:28:14 +01:00
|
|
|
let connections: ConnectionMap = Arc::new(Mutex::new(HashMap::new()));
|
2025-11-11 13:35:34 +01:00
|
|
|
|
2025-11-12 11:28:14 +01:00
|
|
|
while let Ok((stream, _)) = listener.accept().await {
|
|
|
|
|
let connections = connections.clone();
|
2025-11-11 13:35:34 +01:00
|
|
|
tokio::spawn(async move {
|
2025-11-12 11:28:14 +01:00
|
|
|
handle_connection(stream, connections).await;
|
2025-11-11 13:35:34 +01:00
|
|
|
});
|
|
|
|
|
}
|
2025-11-03 14:47:15 +01:00
|
|
|
}
|