我有一个非常简单的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');
}
}
我需要在ConnectionsHandler
中得到request.session
。WebSocketTransformer
似乎只发送WebSocket
连接,不能访问原始HttpRequest
与会话。
是否有办法从websocket处理程序本身访问会话数据?即使客户端发送dart会话id从cookie,如何检索和刷新HttpSession然后?
你可能能够让这个工作,但你只能看到cookie,因此会话,如果web套接字连接使用相同的来源作为正常的HTTP请求。
注意,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);
}