如何从Dart HttpServer WebSocket访问HttpSession数据



我有一个非常简单的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.sessionWebSocketTransformer似乎只发送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);
}

相关内容

  • 没有找到相关文章

最新更新