websocket and data:

This commit is contained in:
maxstrb 2025-11-04 22:41:01 +01:00
parent 964c90d2f2
commit 1893eb0599
5 changed files with 65 additions and 50 deletions

View file

@ -10,7 +10,7 @@ use tokio::io::AsyncWriteExt;
use tokio::net::{TcpListener, TcpStream};
use tokio::time;
use crate::websoket_connection::WebsocketConnection;
use crate::websoket_connection::{FrameType, WebsocketConnection};
use crate::{
request::{Connection, ServerPath},
response::{Response, ResponseCode, ResponseHeader},
@ -50,52 +50,34 @@ async fn handle_http_connection(
break;
}
Err(_) => {
println!("Timed out");
break;
}
};
println!("{req:?}");
// DEBUG: Print the path matching
let matchable = req.path.to_matchable();
println!("Path matchable: {:?}", matchable);
println!("Path as slice: {:?}", matchable.as_slice());
let response = match matchable.as_slice() {
["public", file] => {
println!("Matched public file: {}", file);
match Response::from_file(Path::new(format!("./public/{file}").as_str())) {
Ok(resp) => resp,
Err(_) => Response::new().with_code(ResponseCode::NotFound),
}
}
["websocket"] => {
println!("WebSocket path matched!");
println!("Initializing WebSocket connection...");
match WebsocketConnection::initialize_connection(req, stream).await {
Ok(ws) => {
println!("WebSocket connection established successfully!");
return Ok(Some(ws));
}
Err(e) => {
println!("WebSocket initialization failed: {}", e);
return Err(e);
}
["websocket"] => match WebsocketConnection::initialize_connection(req, stream).await {
Ok(ws) => {
return Ok(Some(ws));
}
}
[] => {
println!("Matched root path, redirecting");
Response::new()
.with_code(ResponseCode::PermanentRedirect)
.with_header(ResponseHeader::Connection(Connection::KeepAlive))
.with_header(ResponseHeader::Location(
ServerPath::from_str("/public/index.html").unwrap(),
))
}
other => {
println!("No match, path was: {:?}", other);
Response::new().with_code(ResponseCode::NotFound)
}
Err(e) => {
return Err(e);
}
},
[] => Response::new()
.with_code(ResponseCode::PermanentRedirect)
.with_header(ResponseHeader::Connection(Connection::KeepAlive))
.with_header(ResponseHeader::Location(
ServerPath::from_str("/public/index.html").unwrap(),
)),
_ => Response::new().with_code(ResponseCode::NotFound),
};
response.respond(&mut stream).await?;
stream.flush().await?;
@ -103,7 +85,6 @@ async fn handle_http_connection(
if req.headers.contains(&request::RequestHeader::Connection(
request::Connection::Close,
)) {
println!("Connection closed");
break;
}
}
@ -114,6 +95,11 @@ async fn handle_websocket(mut web_socket: WebsocketConnection) -> tokio::io::Res
loop {
let message = web_socket.read_next_message().await?;
println!("{:?}", message.data);
if message.frame_type == FrameType::TextFrame {
println!("{}", String::from_utf8_lossy(&message.data));
web_socket
.send_message(FrameType::TextFrame, "message_received".as_bytes())
.await?;
}
}
}