- 确认是否为客户端问题:可以使用其他websocket客户端测试是否出现同样的问题,如果是,则继续下一步;如果不是,则需要检查客户端代码。
- 确认后端代码:检查后端使用的websocket库是否正确配置并支持多个会话。可以考虑使用actix-web的其他websocket库,如tokio-tungstenite。
- 代码示例:
use actix::*;
use actix_web::*;
use actix_web_actors::ws;
use std::collections::HashSet;
struct Lobby {
sessions: HashSet>,
}
impl Default for Lobby {
fn default() -> Self {
Lobby { sessions: HashSet::new() }
}
}
impl Actor for Lobby {
type Context = Context;
}
impl Handler for Lobby {
type Result = ();
fn handle(&mut self, msg: Connect, ctx: &mut Self::Context) {
let my_websocket = MyWebSocket::default().start(ctx);
self.sessions.insert(my_websocket);
msg.addr.do_send(Connected(my_websocket));
}
}
struct MyWebSocket;
impl Default for MyWebSocket {
fn default() -> Self {
MyWebSocket
}
}
impl Actor for MyWebSocket {
type Context = ws::WebsocketContext;
fn started(&mut self, ctx: &mut Self::Context) {
ctx.add_stream(stream::once(Ok(ws::Message::Text(
"You are connected".to_string(),
))));
}
}
impl StreamHandler> for MyWebSocket {
fn handle(&mut self, _msg: Result, _: &mut Self::Context) {
}
}
struct Connect {
addr: Recipient,
}
struct Connected(Addr);
async fn index(req: HttpRequest, stream: web::Payload, srv: web::Data>) -> Result {
let resp = ws::start(MyWebSocket {}, &req, stream, |out| Connect { addr: out });
resp.map(|req| req.on_upgrade(|ws_conn| handle_websocket_connection(ws_conn, srv.get_ref()).map_err(|_| ())))
}
async fn handle_websocket_connection(ws_conn: ws::WebsocketContext, lobby_addr: &Addr) -> Result<(), ws::ProtocolError> {
lobby_addr.do_send(Connect { addr: ws_conn.address() });
Ok(())
}