3个版本
0.1.2 | 2023年8月6日 |
---|---|
0.1.1 | 2023年8月6日 |
0.1.0 | 2023年7月31日 |
#697 in 异步
75KB
1.5K SLoC
reception
此crate提供了一种绑定TCP监听器的方式,该监听器将接受传入的WebSocket连接。此外,它还提供了一个抽象层(参见Client
),用于序列化和反序列化定义良好的模型。
示例
#[derive(Debug)]
struct Model {
payload: Vec<u8>,
}
impl Into<Vec<u8>> for Model {
fn into(self) -> Vec<u8> {
self.payload
}
}
impl TryFrom<Vec<u8>> for Model {
type Error = anyhow::Error;
fn try_from(payload: Vec<u8>) -> Result<Self, Self::Error> {
Ok(Self { payload })
}
}
fn handle_client(
client: Client<Connection<WebSocketStream<TcpStream>>, Model, Model>,
cancellation_token: CancellationToken,
) -> Result<(), Client<Connection<WebSocketStream<TcpStream>>, Model, Model>> {
tokio::spawn(async move {
let (tx, mut rx) = unbounded_channel();
let mut handle = client
.spawn_with_callback(cancellation_token, move |msg| {
tx.send(msg).unwrap();
Ok(())
})
.await;
while let Some(msg) = rx.recv().await {
handle.send(msg).await.unwrap();
}
});
Ok(())
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
let cancellation_token = CancellationToken::new();
let listener =
reception::Listener::<Model, Model>::bind(Default::default(), cancellation_token.clone())
.await?;
let handle = listener
.spawn_with_callback(cancellation_token.clone(), move |client| {
handle_client(client, cancellation_token.clone())
})
.await;
handle.await??;
Ok(())
}
许可证
请参阅LICENSE.txt文件。
依赖关系
~5–14MB
~156K SLoC