1 个不稳定版本
0.1.1 | 2023 年 10 月 15 日 |
---|---|
0.1.0 |
|
#21 in #网络编程
24KB
577 行
tcpnet
适用于 Tokio 的简单基于 tick 的 TCP 消息传输,客户端和服务器提供 send()
和 receive()
方法,分别用于发送数据和轮询事件。
服务器使用示例
use tcpnet::server::{Event, Server};
fn main() {
let mut server = Server::new();
server.start(7000);
assert!(server.running());
// Process events on every tick
for event in server.received().unwrap() {
match event {
Event::Connect(addr) => println!("{} connected", addr),
Event::Disconnect(addr) => println!("{} disconnected", addr),
Event::Data(addr, data) => {
println!("{}: {}", addr, std::str::from_utf8(&data).unwrap());
server.send(addr, "Hello back!".as_bytes().to_vec())?;
}
}
}
}
客户端使用示例
use tcpnet::client::{Event, Client};
fn main() {
let mut client = Client::new();
client.start("127.0.0.1:7000");
assert!(server.running());
// Process events on every tick/frame
for event in server.received().unwrap() {
match event {
Event::Disconnect => println!("Disconnected from server"),
Event::Data(data) => println!("Server: {}", addr, std::str::from_utf8(&data).unwrap()),
}
}
}
依赖项
~2.4–9MB
~57K SLoC