(server) feat:Add TCP server

This commit is contained in:
CaicukunChiji
2025-07-10 18:27:09 +08:00
parent 243a1cb923
commit cd415c0b58
5 changed files with 286 additions and 2 deletions

View File

@ -0,0 +1,31 @@
use tokio::{
io::AsyncWriteExt,
net::{TcpListener, TcpStream},
};
pub(crate) struct TcpServer;
impl TcpServer {
pub(crate) async fn init() {
match TcpListener::bind("127.0.0.1:12345").await {
Ok(listener) => loop {
match listener.accept().await {
Ok((socket, addr)) => {
log::info!("New client connected: {addr}");
tokio::spawn(async { Self::process(socket).await });
}
Err(e) => log::error!("Couldn't get client: {e:?}"),
}
},
Err(e) => log::error!("Failed to bind port: {e:?}"),
}
}
async fn process(mut socket: TcpStream) {
socket
.write_all("Hello from server written in Rust!".as_bytes())
.await
.unwrap();
}
}