我可以从WebSocketConnection实例中提取客户端的IP /端口吗?

时间:2013-01-04 23:38:44

标签: dart

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

我需要此功能的环境是:我有一个处理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){...}

是否有可能在此代码的某处破解此功能?非常感谢你提前!

1 个答案:

答案 0 :(得分: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);
};