#服务器 #数据包 #连接 #客户端 #接收 #套接字地址 #接受

数据包

一个用于编写简单、基于数据包的服务器的库

1 个不稳定版本

0.1.0 2020 年 11 月 25 日

#11#接受

MIT 许可证

22KB
466

数据包

Packets 是一个小型库,它使编写基于数据包的 TCP 服务器和客户端变得更容易。

创建服务器

use packets::*;
use packets::server::*;
use std::net::SocketAddr;

// Bind the server to localhost at port 60000.
let mut server = Server::bind("localhost:60000", &ServerConfig::default()).unwrap();

// Accept all incoming connections.
server.accept_all(); 

// Receive all incoming packets, using String as our packet type.
let packets: Vec<(SocketAddr, String)> = server.receive_all().unwrap();
for (addr, packet) in packets {
  server.send(addr, &packet); // Echo the data back to the client.
}

// Close all connections to the server and consume the Server object.
server.shutdown();

创建客户端

use packets::*;
use packets::client::*;

let mut client = Client::connect("localhost:60000", &ClientConfig::default());

// Receive all incoming packets.
// In this example we use String as our Packet type.
let packets: Vec<String> = client.receive_all();

// Send a packet to the server, using String as our packet type for this example.
client.send("Hello, world!".to_string());

// Shut this client down, consuming it.    
client.shutdown();

依赖关系

~1.1–2MB
~40K SLoC