async fn socket(mut ws: WebSocket, state: Users) {
tokio::spawn(async move {
while let Some(msg) = reader.recv().await{
println!("message for user: {:?}", msg);
ws.send(msg).await.unwrap();
};
});
while let Some(msg) = ws.recv().await{
// not matter
}
}
我需要多次使用 ws 值,一次在流中(tokio::spawn),一次在循环中,但编译器写道该值在移动后使用。
我将循环移至线程,但该函数没有收到消息(不写入“给用户的消息”):
tokio::spawn(async move {
while let Some(msg) = reader.recv().await{
println!("message for user: {:?}", msg);
ws.send(msg).await.unwrap();
};
while let Some(msg) = ws.recv().await{
//not matter
}
});
在我复制代码的示例中,使用了 ws.next() ,但编译器也会引发错误:“next() - 未为 WebSokcet 定义”
axum websocket documentation 有一个示例展示如何同时读写:
use axum::{Error, extract::ws::{WebSocket, Message}};
use futures_util::{sink::SinkExt, stream::{StreamExt, SplitSink, SplitStream}};
async fn handle_socket(mut socket: WebSocket) {
let (mut sender, mut receiver) = socket.split();
tokio::spawn(write(sender));
tokio::spawn(read(receiver));
}
async fn read(receiver: SplitStream<WebSocket>) {
// ...
}
async fn write(sender: SplitSink<WebSocket, Message>) {
// ...
}
关键是将套接字(双向通信通道)分为不同的“流”(读)和“汇”(写)类型。我建议咨询
StreamExt
和 SinkExt
以了解您可以使用这些类型做什么。