我的服务器代码是这样开始的,我想获得客户端IP,无论何时连接,何时断开连接。
List<WebSocket> connections;
void main() {
connections = new List<WebSocket>();
HttpServer.bind(HOST, PORT).then((HttpServer server) {
print('Server listening on port ${PORT}.');
server.listen((HttpRequest request) {
if (WebSocketTransformer.isUpgradeRequest(request)) {
WebSocketTransformer.upgrade(request).then(handleWS);
} else gotMSG(request);
});
});
}
handleWS(WebSocket ws){
connections.add(ws);
print('Client connected, there are now ${connections.length} client(s) connected.');
ws.listen((String message) {
for (WebSocket connection in connections) {
connection.add(message);
}
},
onDone: () {
connections.remove(ws);
print('Client disconnected, there are now ${connections.length} client(s) connected.');
});
}
有什么想法吗?
我看不出有任何方法可以从WebSocket
获取IP,但您可以从HttpRequest
获取IP并从那里传入;类似这样的东西(注意:我无法运行这个,所以你可能需要调整它才能工作):
// in main()...
// Pass client IP into handleWS, which now returns the function
webSocketTransformer.upgrade(request)
.then(handleWS(request.connectionInfo.remoteAddress));
// handleWS now takes the IP, and then returns the original function,
// which now has clientAddress in scope.
handleWS(InternetAddress clientAddress) {
return (WebSocket ws) {
connections.add(ws);
print('Client $clientAddress connected, there are now ${connections.length} client(s) connected.');
ws.listen(
(String message) {
for (WebSocket connection in connections) {
connection.add(message);
}
},
onDone: () {
connections.remove(ws);
print('Client $clientAddress disconnected, there are now ${connections.length} client(s) connected.');
}
);
};
}
我就是这样做的。注意.connectionInfo
的使用
HttpServer.bind(InternetAddress.ANY_IP_V4,8090).then((HttpServer server) {
print("HttpServer listening at ${server.address}:${server.port}...");
server.serverHeader = "EventDashboard Socket server by Jan D.";
server.listen((HttpRequest request) {
if (WebSocketTransformer.isUpgradeRequest(request)) {
print(request.connectionInfo.remoteAddress);
WebSocketTransformer.upgrade(request).then(handleWebSocket);
}
else {
print("Regular ${request.method} request for: ${request.uri.path}");
request.response.statusCode = HttpStatus.FORBIDDEN;
request.response.reasonPhrase = "WebSocket connections only";
request.response.close();
}
});