websocket not working

This commit is contained in:
maxstrb 2025-11-04 18:02:59 +01:00
parent 46ad5b3bf7
commit 964c90d2f2
5 changed files with 136 additions and 54 deletions

View file

@ -33,7 +33,6 @@ async fn handle_connection(stream: TcpStream) -> tokio::io::Result<()> {
Ok(())
}
async fn handle_http_connection(
mut stream: TcpStream,
) -> tokio::io::Result<Option<websoket_connection::WebsocketConnection>> {
@ -46,8 +45,8 @@ async fn handle_http_connection(
.await
{
Ok(Ok(r)) => r,
Ok(Err(_)) => {
println!("Wrong request");
Ok(Err(e)) => {
println!("Wrong request: {e}");
break;
}
Err(_) => {
@ -55,37 +54,52 @@ async fn handle_http_connection(
break;
}
};
println!("{req:?}");
let response = match req.path.to_matchable().as_slice() {
// 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"] => {
return Ok(Some(
WebsocketConnection::initialize_connection(req, stream).await?,
));
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);
}
}
}
[] => {
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)
}
[] => 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?;
timeout = 5000;
if req.headers.contains(&request::RequestHeader::Connection(
request::Connection::Close,
)) {
@ -93,10 +107,13 @@ async fn handle_http_connection(
break;
}
}
Ok(None)
}
async fn handle_websocket(mut web_socket: WebsocketConnection) -> tokio::io::Result<()> {
todo!()
loop {
let message = web_socket.read_next_message().await?;
println!("{:?}", message.data);
}
}