2

给定一个实例,有什么方法WebSocketConnection可以提取它所代表的客户端的 IP/端口?我知道实现(即_WebSocketConnectionBase)具有 aSocket作为私有变量,但我无法破解它。有什么解决方法吗?

我需要这个功能的环境是这样的:我有一个处理 Web 套接字连接的服务器,我想将客户端的 IP 存储在他们的 Web 套接字旁边。我像这样实例化我的服务器:

var server = new HttpServer();
var wsHandler = new WebSocketHandler();

wsHandler.onOpen = this.subscribeUser;
server.addRequestHandler((req) => req.path == "/ws", wsHandler.onRequest);
...
subscribeUser(WebSocketConnection user){...}

是否有可能在这段代码的某个地方破解这个功能?非常感谢您!

4

1 回答 1

1

您可以尝试对 WebSocketHandler 进行扩展实现并从此处获取请求。一个例子:

class betterWebSocket implements WebSocketHandler {
  WebSocketHandler _wsHandler = new WebSocketHandler();

  void onRequest(HttpRequest request, HttpResponse response) {
    print(request.connectionInfo.remoteHost); // Print the IP of the remote to the screen
    _wsHandler.onRequest(request, response);
  }

  void set onOpen(callback(WebSocketConnection connection)) {
    _wsHandler.onOpen = callback;
  }
}

您可以将此类用作普通的 WebSocketHandler:

void main() {
  HttpServer server = new HttpServer();
  betterWebSocket wsHandler = new betterWebSocket();

  server.addRequestHandler((req) => req.path == "/", wsHandler.onRequest);

  wsHandler.onOpen = (WebSocketConnection conn) {
    print("New connection");

    conn.onMessage = (message) {
      print("message is $message");
    };

    conn.onClosed = (int status, String reason) {
      print('closed with $status for $reason');
    };

  server.listen('127.0.0.1', 20024);
};
于 2013-01-06T21:18:00.923 回答