bincode gaming

This commit is contained in:
2025-11-16 23:06:51 -05:00
parent 3ecd7a5565
commit 8a9e766633
7 changed files with 194 additions and 95 deletions

View File

@@ -1,74 +1,20 @@
use crate::net::{ClientMsg, server::listen};
use tracing::Instrument;
use crate::net::{
ClientMsg,
server::{ConHandler, listen},
};
#[tokio::main]
pub async fn run_server() {
let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
let path = dirs.data_local_dir();
let endpoint = listen(path);
println!("listening on {}", endpoint.local_addr().unwrap());
let handler = ClientHandler {};
listen(path, handler).await;
}
while let Some(conn) = endpoint.accept().await {
let fut = handle_connection(conn);
tokio::spawn(async move {
if let Err(e) = fut.await {
eprintln!("connection failed: {reason}", reason = e)
}
});
pub struct ClientHandler {}
impl ConHandler for ClientHandler {
fn on_msg(&self, msg: ClientMsg) {
println!("received msg: {msg:?}");
}
}
async fn handle_connection(conn: quinn::Incoming) -> std::io::Result<()> {
let connection = conn.await?;
let span = tracing::info_span!(
"connection",
remote = %connection.remote_address(),
protocol = %connection
.handshake_data()
.unwrap()
.downcast::<quinn::crypto::rustls::HandshakeData>().unwrap()
.protocol
.map_or_else(|| "<none>".into(), |x| String::from_utf8_lossy(&x).into_owned())
);
async {
// Each stream initiated by the client constitutes a new request.
loop {
let stream = connection.accept_bi().await;
// let time = Instant::now();
let stream = match stream {
Err(quinn::ConnectionError::ApplicationClosed { .. }) => {
println!("connection closed");
return Ok(());
}
Err(e) => {
return Err(e);
}
Ok(s) => s,
};
tokio::spawn(
async move {
if let Err(e) = handle_stream(stream).await {
eprintln!("failed: {reason}", reason = e);
}
}
.instrument(tracing::info_span!("request")),
);
}
}
.instrument(span)
.await?;
Ok(())
}
async fn handle_stream(
(send, mut recv): (quinn::SendStream, quinn::RecvStream),
) -> Result<(), String> {
drop(send);
let bytes = recv
.read_to_end(std::mem::size_of::<ClientMsg>())
.await
.map_err(|e| format!("failed reading request: {}", e))?;
let msg = String::from_utf8(bytes).unwrap();
println!("received message: {:?}", msg);
Ok(())
}