1 个不稳定版本
0.1.1 | 2024 年 5 月 31 日 |
---|---|
0.1.0 |
|
#10 in #listen
每月 33 次下载
10KB
140 行
lstnconn
网络监听器生成连接的抽象
lib.rs
:
use lstnconn::{
Handler, ListenConnMgr, async_trait, Stream, ConnInfo, Handle,
KillSwitch, Listener
};
// Handler used to process connections
struct MyHandler { }
// Per-connection data type
#[derive(Clone)]
struct ConnectData { }
#[async_trait]
impl Handler for MyHandler {
type ConnCtx = ConnectData;
async fn connected(&self, ci: ConnInfo) -> Handle<Self::ConnCtx> {
// A connection has been established, tell listener to spawn a new task
// for running connection handler on.
Handle::Task(ConnectData {})
}
async fn run(&self, conn: Stream, cctx: &mut Self::ConnCtx) {
// .. process the server connection here ..
}
async fn disconnected(&self, cctx: Self::ConnCtx) {
// .. a connection has terminated ..
}
}
let handler = MyHandler { };
let lcm = ListenConnMgr::new(handler);
// Create a KillSwitch for terminating the listener loop
let ks = KillSwitch::new();
// Create a localhost Listener using a system-assigned port
let listener = Listener::tcp("127.0.0.1:0").unwrap();
// Run the listen/connection loop in a background task
task::spawn(lcm.run(listener, ks));
依赖项
~12–22MB
~385K SLoC