我的服务器代码从这样开始,我希望获得客户端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.');
});
}
有什么想法吗?
答案 0 :(得分:1)
我无法看到从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.');
}
);
};
}
答案 1 :(得分:0)
我就是这样做的。请注意使用.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();
}
});