#udp #stream #tokio #uot

forky-udpflow

tokio-udp的流API

2个不稳定版本

0.2.0 2023年6月7日
0.1.0 2023年6月3日

#114 in #udp

Download history 6/week @ 2024-03-08 3/week @ 2024-03-15 3/week @ 2024-03-22 34/week @ 2024-03-29 14/week @ 2024-04-05 2/week @ 2024-05-17

91 每月下载量
uki 中使用

MIT 协议

23KB
447

UDPflow

crates.io Released API docs

tokio-udp的流API。

类似TCP的UDP流

use tokio::net::UdpSocket;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use udpflow::{UdpListener, UdpStreamLocal, UdpStreamRemote};
async fn server() {
    let addr = "127.0.0.1:5000".parse().unwrap();
    let listener = UdpListener::new(addr).unwrap();
    loop {
        let mut buf = vec![0u8; 0x2000];
        let (n, stream, addr) = listener.accept(&mut buf).await.unwrap();
        buf.truncate(n);
        tokio::spawn(handle(stream, buf));
    }
}

async fn handle(mut stream1: UdpStreamLocal, first_packet: Vec<u8>) {
    let local = "127.0.0.1:0".parse().unwrap();
    let remote = "127.0.0.1:10000".parse().unwrap();
    let mut stream2 = UdpStreamRemote::new(local, remote).await.unwrap();
    stream2.write_all(&first_packet).await.unwrap();
    let mut buf = vec![0u8; 256];
    stream1.read(&mut buf).await; stream2.write(&buf).await;
    stream2.read(&mut buf).await; stream1.write(&buf).await;
}

发送/接收分帧数据

use tokio::net::TcpStream;
use udpflow::UotStream;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
async {
    let stream = TcpStream::connect("127.0.0.1:8080").await.unwrap();
    let mut stream = UotStream::new(stream);
    let mut buf = vec![0u8; 256];
    // read a frame
    let n = stream.read(&mut buf).await.unwrap();
    // write a frame
    stream.write_all(&buf[..n]).await;
};

UoT规范

+------+----------+
| LEN  |   DATA   |
+------+----------+
|  2   | Variable |
+------+----------+

*LEN是一个16位无符号整数,采用大端字节序。

依赖项

~3–14MB
~115K SLoC