Started to rewrite the project to handle connection storing and message types, added v4 for uuid crate

This commit is contained in:
2025-11-12 11:28:14 +01:00
parent 503cb23015
commit 4daa21e8bf
3 changed files with 55 additions and 25 deletions

View File

@@ -0,0 +1,33 @@
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{accept_async, tungstenite::Message as WsMessage};
use uuid::Uuid;
use crate::ConnectionMap;
async fn handle_connection(stream: tokio::net::TcpStream, connections: ConnectionMap) {
let ws_stream = accept_async(stream).await.unwrap();
let (write, mut read) = ws_stream.split();
let id = Uuid::new_v4();
{
let mut map = connections.lock().await;
map.insert(id, write);
}
println!("New connection: {id}");
while let Some(Ok(msg)) = read.next().await {
if msg.is_text() {
println!("Recieved from {id}: {}", msg);
broadcast_message(&connections, &msg).await;
}
}
{
let mut map = connections.lock().await;
map.remove(&id);
}
println!("Connection removed: {id}");
}

View File

@@ -1,44 +1,40 @@
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio_tungstenite::{accept_async, connect_async};
use url::Url;
use tokio::sync::Mutex;
use tokio_tungstenite::accept_async;
use uuid::Uuid;
mod handle_connection;
#[derive(Serialize, Deserialize, Debug)]
struct Message {
struct MessageData {
username: String,
userid: u32,
text: String,
}
type Tx = futures_util::stream::SplitSink<
tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>,
tokio_tungstenite::tungstenite::Message,
>;
type ConnectionMap = Arc<Mutex<HashMap<Uuid, Tx>>>;
#[tokio::main]
async fn main() {
let address = "0.0.0.0:9001"; //accept connection from anywhere
let address = "0.0.0.0:9001"; //address to connect to
let listener = TcpListener::bind(address).await.unwrap();
println!("Server running on ws://{}", address);
let connections: ConnectionMap = Arc::new(Mutex::new(HashMap::new()));
while let Ok((stream, _)) = listener.accept().await {
println!("New connection!");
let connections = connections.clone();
tokio::spawn(async move {
let ws_stream = accept_async(stream).await.unwrap();
let (mut write, mut read) = ws_stream.split(); //seperate the read and write channel
while let Some(Ok(msg)) = read.next().await {
if msg.is_text() {
let txt = msg.to_text().unwrap();
if let Ok(json) = serde_json::from_str::<Message>(txt) {
println!("Recieved: {:?}", json);
//for testing the write channel, we send back the
//same data the client sent
let reply = serde_json::to_string(&json).unwrap();
write
.send(tokio_tungstenite::tungstenite::Message::Text(reply))
.await
.unwrap();
}
}
}
handle_connection(stream, connections).await;
});
}
}