aqueduct
aqueduct copied to clipboard
Aqueduct WebSocket Issue
I am trying to save open connections in a map but every time a new request came, my map reset and it only show's the last connection. I am writing this code in "*_sink.dart" file.
final Map<String, WebSocket> connections = new Map<String, WebSocket>();
router
.route("/connect")
.listen((req) async {
if (!WebSocketTransformer.isUpgradeRequest(req.innerRequest)) {
return new Response.badRequest();
}else{
String name = req.innerRequest.uri.queryParameters["uid"];
WebSocket webSocket;
if(connections[name] != null){
//TODO: check state of socket before using
webSocket = connections[name];
}else{
webSocket = await WebSocketTransformer.upgrade(req.innerRequest);
connections[name] = webSocket;
}
print("Open Connection: ${connections.length}");
webSocket.listen((event) {
// send back whatever we received
webSocket.add(event);
});
}
});
It always shows "Open Connection: 1".
How many isolates are you running on? The app's RequestSink is instantiated for each isolate, so you may have more than one connections map. Depending on which isolate receives the new request, the websocket will be added to only that associated RequestSink's connections map.
For an easy solve, try running the application with aqueduct serve --isolates 1.