2

我有一个非常简单的 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进去ConnectionsHandlerWebSocketTransformer似乎只发送WebSocket无权访问原始HttpRequest会话的连接。

有没有办法从 websocket 处理程序本身访问会话数据?即使客户端从 cookie 发送 dart 会话 id,那么如何检索和刷新 HttpSession 呢?

4

1 回答 1

2

你也许可以让它工作,但你只能看到 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);
}
于 2013-04-18T05:24:19.700 回答