#tokio #tcp #unix-socket #async #uds

异步流连接

支持TCP以及Unix套接字的AsyncRead和AsyncWrite

2个稳定版本

1.0.1 2023年5月12日

#10 in #uds


2 crates中使用

MIT 许可证

17KB
354

Project Status: Active – The project has reached a stable, usable state and is being actively developed. crates.io Released API docs GitHub GitHub Workflow Status

一个简单的枚举,支持在TCP以及Unix套接字上使用tokio::io::AsyncReadtokio::io::AsyncWrite


lib.rs:

一个简单的枚举,支持tokio::io::AsyncReadtokio::io::AsyncWrite在TCP以及Unix套接字上。 * *

  • 示例

  • 一个简单的TCP回显服务器
  • use async_stream_connection::Listener;
  • use tokio::io::{AsyncReadExt, AsyncWriteExt};
  • #[tokio::main(flavor = "current_thread")]
  • async fn main() -> Result<(), Box> {
  •  let listener = Listener::bind(&"127.0.0.1:8080".parse()?).await?;
    
  •  loop {
    
  •      let (mut socket, _) = listener.accept().await?;
    
  •      tokio::spawn(async move {
    
  •          let mut buf = [0; 1024];
    
  •          // In a loop, read data from the socket and write the data back.
    
  •          loop {
    
  •              let n = match socket.read(&mut buf).await {
    
  •                  // socket closed
    
  •                  Ok(n) if n == 0 => return,
    
  •                  Ok(n) => n,
    
  •                  Err(e) => {
    
  •                      eprintln!("failed to read from socket; err = {:?}", e);
    
  •                      return;
    
  •                  }
    
  •              };
    
  •              // Write the data back
    
  •              if let Err(e) = socket.write_all(&buf[0..n]).await {
    
  •                  eprintln!("failed to write to socket; err = {:?}", e);
    
  •                  return;
    
  •              }
    
  •          }
    
  •      });
    
  •  }
    
  • }
  • 
    

依赖

~2–14MB
~112K SLoC