我有一个非常简单的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呢?
答案 0 :(得分:2)
您可能能够使其工作,但如果Web套接字连接使用与普通HTTP请求相同的源,您只能看到cookie,从而只能看到会话。
请注意,WebSocketTransformer
不必在流中使用。您可以一次升级一个请求。
您可以尝试以下代码吗?
import 'dart:io';
import 'dart:async';
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 connHandler = new ConnectionsHandler();
var webSocketTransformer = new WebSocketTransformer();
server.listen((HttpRequest request) {
if (request.uri.path == '/ws') {
webSocketTransformer.upgrade(request)
.then((WebSocket ws) {
connHandler.onConnection(ws, request);
});
// TODO handle error from update
}
// 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, HttpRequest req) {
print('new ws conn');
connections.add(conn);
conn.listen(
(message) {
print('new ws msg: $message and ${req.session.keys}');
},
onDone: () => connections.remove(conn),
onError: (e) => connections.remove(conn)
);
}
}
main() {
var server = new WsServer();
server.runServer(3000);
}