我正在学习Rust,并试图编写一个websocket服务器。逻辑如下:WSConnectionFactory创建WSHandler,该Handler处理传入消息并根据任意规则将它们发送给其他客户端。
问题是我不知道如何实现这种行为。
限制:我不能更改Factory和Handler特性的签名,因为它们是由ws-rs库提供的。
问题:如何使用RefCell/Cell来实现?
extern crate rand;
extern crate rustc_serialize;
extern crate ws;
#[macro_use]
extern crate log;
#[macro_use]
extern crate env_logger;
use std::cell::RefCell;
use std::collections::HashMap;
use rand::random;
use ws::{Factory, Sender, Handler, Handshake, Message, CloseCode, WebSocket};
use ws::Result as WSResult;
use ws::util::Token;
struct WSConnectionFactory<'p> {
handlers: HashMap<&'p u32, RefCell<&'p WSHandler<'p>>>,
}
#[derive(Debug)]
struct WSHandler<'h> {
uid: &'h u32,
ws: RefCell<&'h Sender>,
}
impl<'p> Factory for WSConnectionFactory<'p> {
type Handler = WSHandler<'p>;
fn connection_made(&mut self, ws: Sender) -> Self::Handler {
println!("factory.connection_made token={:?}", &ws.token());
let uid = &random::<u32>();
let handler = WSHandler {
uid: uid,
ws: RefCell::new(&ws),
};
self.handlers.insert(uid, RefCell::new(&handler));
handler
}
}
impl<'h> Handler for WSHandler<'h> {
fn on_open(&mut self, _handshake: Handshake) -> WSResult<()> {
println!("handler.on_open");
Ok(())
}
fn on_message(&mut self, msg: Message) -> WSResult<()> {
println!("handler.on_message {:?}", msg);
Ok(())
}
fn on_timeout(&mut self, _token: Token) -> WSResult<()> {
println!("handler.on_timeout {:?}", _token);
Ok(())
}
fn on_close(&mut self, code: CloseCode, reason: &str) {
println!("handler.on_close code={:?}, reason={:?}", code, reason);
}
}
fn main() {
let factory = WSConnectionFactory { handlers: HashMap::new() };
let ws_socket = WebSocket::new(factory).expect("Can't create WebSocket");
ws_socket.listen("127.0.0.1:8080").expect("Can't bind to socket");
}
最佳答案
您试图从WSHandler
返回connection_made
,同时还在WSHandler
结构中存储对WSConnectionFactory
的引用。这是不可能的(使用借来的指针),因为通过返回WSHandler
,您无法控制将发生的事情(它可能会移动或掉落,这会使您的指针无效)。当您只应直接存储值时,您还将存储借用的指针。
如果要向其他客户端发送消息,则实际上需要 Sender
,而不是WSHandler
。值得庆幸的是,Sender
实现了Clone
,并且从快速浏览代码的角度来看,克隆Sender
应该为您提供了指向同一端点的第二个“句柄”。因此,您应该在Sender
中放置一个HashMap
,而不是WSHandler
。
extern crate rand;
extern crate rustc_serialize;
extern crate ws;
#[macro_use]
extern crate log;
#[macro_use]
extern crate env_logger;
use std::collections::HashMap;
use rand::random;
use ws::{Factory, Sender, Handler, Handshake, Message, CloseCode, WebSocket};
use ws::Result as WSResult;
use ws::util::Token;
struct WSConnectionFactory {
handlers: HashMap<u32, Sender>,
}
#[derive(Debug)]
struct WSHandler {
uid: u32,
ws: Sender,
}
impl Factory for WSConnectionFactory {
type Handler = WSHandler;
fn connection_made(&mut self, ws: Sender) -> Self::Handler {
println!("factory.connection_made token={:?}", &ws.token());
let uid = random::<u32>();
let handler = WSHandler {
uid: uid,
ws: ws.clone(),
};
self.handlers.insert(uid, ws);
handler
}
}
impl Handler for WSHandler {
fn on_open(&mut self, _handshake: Handshake) -> WSResult<()> {
println!("handler.on_open");
Ok(())
}
fn on_message(&mut self, msg: Message) -> WSResult<()> {
println!("handler.on_message {:?}", msg);
Ok(())
}
fn on_timeout(&mut self, _token: Token) -> WSResult<()> {
println!("handler.on_timeout {:?}", _token);
Ok(())
}
fn on_close(&mut self, code: CloseCode, reason: &str) {
println!("handler.on_close code={:?}, reason={:?}", code, reason);
}
}
fn main() {
let factory = WSConnectionFactory { handlers: HashMap::new() };
let ws_socket = WebSocket::new(factory).expect("Can't create WebSocket");
ws_socket.listen("127.0.0.1:8080").expect("Can't bind to socket");
}
关于rust - 如何在哈希映射字段中保存对处理程序的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36817663/