summaryrefslogtreecommitdiff
path: root/examples/echo.rs
diff options
context:
space:
mode:
authorihciah <[email protected]>2021-11-28 01:46:23 +0800
committerihciah <[email protected]>2021-11-29 16:05:45 +0800
commit54d9885220d2e0cd0167f6cbb10c7b0d9e762df2 (patch)
tree392992a5ee3d531018bf55c12305e0ebc2ce984a /examples/echo.rs
init
Diffstat (limited to 'examples/echo.rs')
-rw-r--r--examples/echo.rs37
1 files changed, 37 insertions, 0 deletions
diff --git a/examples/echo.rs b/examples/echo.rs
new file mode 100644
index 0000000..644627a
--- /dev/null
+++ b/examples/echo.rs
@@ -0,0 +1,37 @@
+//! Echo example.
+//! Use `nc 127.0.0.1 30000` to connect.
+
+use futures::StreamExt;
+use mini_rust_runtime::executor::Executor;
+use mini_rust_runtime::tcp::TcpListener;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+fn main() {
+ let ex = Executor::new();
+ ex.block_on(serve);
+}
+
+async fn serve() {
+ let mut listener = TcpListener::bind("127.0.0.1:30000").unwrap();
+ while let Some(ret) = listener.next().await {
+ if let Ok((mut stream, addr)) = ret {
+ println!("accept a new connection from {} successfully", addr);
+ let f = async move {
+ let mut buf = [0; 4096];
+ loop {
+ match stream.read(&mut buf).await {
+ Ok(n) => {
+ if n == 0 || stream.write_all(&buf[..n]).await.is_err() {
+ return;
+ }
+ }
+ Err(_) => {
+ return;
+ }
+ }
+ }
+ };
+ Executor::spawn(f);
+ }
+ }
+}