From 51cfafb7ec96094e90718eaa8ed1a4d126930789 Mon Sep 17 00:00:00 2001 From: lsy Date: Thu, 17 Oct 2024 01:15:58 +0800 Subject: [PATCH] =?UTF-8?q?HTTP=E6=9C=8D=E5=8A=A1=E5=99=A8=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E7=9B=91=E5=90=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/temp/src/core/mod.rs | 42 +++++++++++++++++++++++++++++++++++++++ rust/temp/src/main.rs | 7 +++++++ 2 files changed, 49 insertions(+) create mode 100644 rust/temp/src/core/mod.rs create mode 100644 rust/temp/src/main.rs diff --git a/rust/temp/src/core/mod.rs b/rust/temp/src/core/mod.rs new file mode 100644 index 0000000..b4a49c8 --- /dev/null +++ b/rust/temp/src/core/mod.rs @@ -0,0 +1,42 @@ +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::{net, runtime}; +use tokio::sync; + + +pub struct Server { + listener_addr: &'static str, + listener_port: i32, + status: bool, + route_vec:Vec<(&'static str,&'static str)>, +} +impl Server { + pub fn new(listener_port:i32) -> Self { + if listener_port < 1 || listener_port > 65535 { + panic!("listener port must be between 1 and 65535"); + } + Self { + listener_addr: "127.0.0.1", + listener_port, + status: false, + route_vec: Vec::new(), + } + } + pub fn start(&self) { + let address=format!("{}:{}", self.listener_addr, self.listener_port); + let rt = runtime::Runtime::new().unwrap(); + println!("Listening on {}", address); + let listener =rt.block_on(async { net::TcpListener::bind(address).await.expect("Failed to bind listener") }); + rt.block_on(Self::receive(listener)) + } + async fn receive(listener:net::TcpListener) { + loop { + let (mut socket, _) = listener.accept().await.expect("Failed to accept connection"); + tokio::spawn(async move { + println!("监听成功"); + let mut buf = [0; 1024]; + socket.read(&mut buf).await.unwrap(); + socket.write_all(b"Hello, World!").await.unwrap(); + }); + } + } +} \ No newline at end of file diff --git a/rust/temp/src/main.rs b/rust/temp/src/main.rs new file mode 100644 index 0000000..1f7d100 --- /dev/null +++ b/rust/temp/src/main.rs @@ -0,0 +1,7 @@ +use core::Server; +mod core; + +fn main() { + let server = core::Server::new( 8000); + server.start(); +} \ No newline at end of file