Reputation: 21511
I'm using a websocket (socket from dart:html
) and I wanted to know if I could send a message when the user closes the browser or exits the page.
I tried the onClose
event like this:
ws = new WebSocket('ws://$hostname:$port/ws');
ws.onOpen.listen(onSocketOpen);
ws.onClose.listen((e) {
ws.send("I disconnected");
});
but it won't send anything in these particular cases. Alternatively, on my server I tried this as well, but with the onDone
event :
WebSocketTransformer.upgrade(req)
..then((socket) => socket.listen((msg) => doSomething(), onDone:() => print("connection closed)));
That works, but I'd like to know what client disconnected (the reason why I wanted to send something from the actual disconnecting client).
Is there a reason to do that? I really don't feel like querying all other clients to know if they're still connected when someone disconnects...
Upvotes: 1
Views: 507
Reputation: 941
On the server side, I like to use a data structure that associates a particular connection with a user, then I don't need the client to identify itself as it closes, because I can figure out which client it was using the connection that triggered the onDone(). The simplest way might be to use a Map like this:
Map<String, WebSocket>
In that case, the String is the client ID (or whatever). It's even possible to do it the other way around:
Map<WebSocket, String>
Your onDone() handler will have a WebSocket passed to it, and you can just look that up in your data structure to find out which client is associated with it.
Note that for this to work, your clients need to send identifying information as the first order of business once they're connected. When they do, you just create the association in your Map.
Clear as mud?
Upvotes: 5
Reputation: 657977
As far as I know window.onBeforeUnload
is the right event. There are some limitations what is allowed for this eventhandler. For example it is not possible to prevent window closing.
Upvotes: 1