使用Rust火箭的Im学习网,但我可以提到的参考代码很少。 火箭“ws”提供的例子代码只能向发送者传递信息。
#[get("/echo")]
fn echo(ws: ws::WebSocket) -> ws::Channel< static> {
ws.channel(move |mut stream| Box::pin(async move {
while let Some(message) = stream.next().await {
let _ = stream.send(message?).await;
}
Ok(())
}))
}
但我要向其他客户传达信息。 因此,你想写一下一点小mo,只是向与这一轮服务器有联系的所有同侪客户发送电 whi。
我试图利用哈希姆普,但失败。 我认为,这一解决办法根本不正确。
use futures::{SinkExt, StreamExt};
use rocket::{get, routes, State, data::IoStream};
use ws::stream::DuplexStream;
use tokio::sync::Mutex;
use std::{net::SocketAddr, sync::{Arc}, collections::HashMap};
type PeersMap = Arc<Mutex<HashMap<SocketAddr, i32>>>;
mod entity;
// static USER_MAP: Arc<Mutex<HashMap<i32, DuplexStream>>> = Arc::new(Mutex::new(HashMap::new()));
#[get("/<user_id>")]
async fn ws_test< a>(user_id: i32, socket: ws::WebSocket, user_map: & a State<Arc<Mutex<HashMap<i32, DuplexStream>>>>) -> ws::Channel< a> {
socket.channel(move |stream| Box::pin(async move {
user_map.lock().await.insert(user_id, stream);
if let Some(stream) = user_map.lock().await.get_mut(&user_id) {
while let Some(message) = stream.next().await {
// let target = user_map.lock().unwrap().get(k);
dbg!(&message);
match message {
Ok(res) => {
if let ws::Message::Text(concrete) = res {
let received_message: entity::ReceivedMessage = serde_json::from_str(&concrete).unwrap();
let target_id = received_message.get_target_id().parse::<i32>().unwrap();
// let message =
match user_map.lock().await.get_mut(&target_id) {
Some(target_stream) => {
let _ = stream.send(ws::Message::Text(concrete.clone())).await;
let _ = target_stream.send(ws::Message::Text(concrete)).await;
},
None => println!("only support text message"),
};
}
},
Err(err) => println!("{err}"),
}
}
}
Ok(())
}))
}
#[rocket::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// let peers: PeerMap = Arc::new(Mutex::new(HashMap::new()));
let user_map: Arc<Mutex<HashMap<i32, DuplexStream>>> = Arc::new(Mutex::new(HashMap::new()));
rocket::build()
.manage(user_map)
.mount("/ws", routes![ws_test])
.launch().await?;
Ok(())
}