我有一个非常简单的 WebSocket 服务器:
class WsServer {
WsServer();
void runServer(int port) {
ConnectionsHandler connectionsHandler = new ConnectionsHandler();
HttpServer
.bind('127.0.0.1', port)
.then((HttpServer server) {
print('listening for connections on $port');
var sc = new StreamController();
sc.stream.transform(new WebSocketTransformer()).listen(connectionsHandler.onConnection);
server.listen((HttpRequest request) {
if (request.uri.path == '/ws') {
sc.add(request);
}
// we dont deal static files
});
},
onError: (error) => print("Error starting HTTP server: $error"));
}
}
class ConnectionsHandler {
List<WebSocket> connections = new List<WebSocket>();
ConnectionsHandler();
void onConnection(WebSocket conn) {
print('new ws conn');
connections.add(conn);
conn.listen(
onMessage,
onDone: () => connections.remove(conn),
onError: (e) => connections.remove(conn)
);
}
void onMessage(message) {
print('new ws msg: $message');
}
}
我需要request.session
进去ConnectionsHandler
。WebSocketTransformer
似乎只发送WebSocket
无权访问原始HttpRequest
会话的连接。
有没有办法从 websocket 处理程序本身访问会话数据?即使客户端从 cookie 发送 dart 会话 id,那么如何检索和刷新 HttpSession 呢?