7个版本
使用旧的Rust 2015
0.0.7 | 2015年1月14日 |
---|---|
0.0.6 | 2015年1月12日 |
0.0.5 | 2014年12月22日 |
#27 in #client-connect
16KB
265 行
superchan
superchan
是一个非常实验性的Rust包,提供用于网络通信的类似通道的构造,主要作为一种学习网络和API设计的方式。
lib.rs
:
Superchan!
此包提供一组类型,模仿Rust的本地通道,但可用于网络通信。
使用 superchan
启动服务器的示例
// server.rs
extern crate "rustc-serialize" as rustc_serialize;
extern crate superchan;
use superchan::tcp::server_channel;
#[derive(Encodable, Decodable)]
enum Message {
Good,
Bad,
}
#[derive(Encodable, Decodable)]
enum Response {
Ok,
NotOk,
}
// Take the client's message and return a response.
// This version is obviously pretty contrived, but
// you get the idea.
fn on_msg(client_id: u32, msg: Message) -> Response {
match msg {
Message::Good => Response::Ok,
Message::Bad => Response::NotOk,
}
}
fn on_new(client_id: u32) {
println!("New client has connected: {}", client_id);
}
fn on_drop(client_id: u32) {
println!("Client has disconnected: {}", client_id);
}
fn main() {
if let Err(e) = server_channel("127.0.0.1:8080", on_msg, on_new, on_drop) {
println!("Failed to start server: {}", e);
}
}
并创建一个客户端连接到它(理想情况下,共享的 Message
和 Response
枚举应在单独的crate中,并由两个crate引用,但为了简单起见,它们在这里重复了)
// client.rs
extern crate "rustc-serialize" as rustc_serialize;
extern crate superchan;
use superchan::{Sender, Receiver};
use superchan::tcp::client_channel;
#[derive(Encodable, Decodable)]
enum Message {
Good,
Bad,
}
#[derive(Encodable, Decodable)]
enum Response {
Ok,
NotOk,
}
fn main() {
let (mut sender, mut receiver) = match client_channel("127.0.0.1:8080") {
Ok(chans) => chans,
Err(e) => { println!("Failed to connect to server: {}", e); return; },
};
// Now we can communicate with the server along the received channels.
sender.send(Message::Good);
match receiver.recv() {
Response::Ok => println!("ok!"),
Response::NotOk => println!("not ok..."),
}
}
目前只支持TCP协议,但很快将添加UDP和其他协议。届时,需要更改的只是将 "tcp" 替换为您选择的协议的 use
语句。
依赖项
~485KB
~11K SLoC