There's a disconnect event that fires whenever a socket.io connection dies (note that you need it because you can still have a wep page, but what if your internet connection dies?). Try the following:
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.on('disconnect', function () { io.sockets.emit('user disconnected'); }); });
on your server. Taken from the Socket.IO website .
// EDIT
So, I looked at your code and did some tests at home. I got the same results as you, and here are my explanations. You are trying to make Socket.IO very dynamic by dynamically making it listen to different URLs (which are added at runtime). But when the first connection occurs, the server does not listen on another URL. It seems that it is at this moment (when the connection is accepted) that the disconnect handler is installed for the first connection and does not update later (note that Socket.IO does not create new connections when you call io.connect many times on the client side). All in all, this seems like a mistake! Or maybe there is some kind of bizarre explanation of why this behavior should be the way it is, but I donβt know that.
Let me tell you something else. First of all, this dynamic creation of listeners doesn't seem to be a good way. In my opinion, you should do the following: store existing rooms and use one URL for all. Hold the room identifier, and when you select, for example, the message event from the client, add the room identifier to the data and process it with one message handler on the server. I think you get the point. Click the dynamic part on the data, not the URL. But I could be wrong, at least my opinion.
Another thing is that the code you wrote seems to be bad. Note that running .on('connection', handler) many times will make it fire many times. Handlers stack one on top of another; they do not replace each other. So here is how I could implement this:
var io = require("socket.io").listen(app); var roomIds = []; function update_listeners(id) { io.of("/"+id).on("connection", function(socket) { console.log("I'm in room " + id); socket.on("disconnect", function(s) { console.log("Disconnected from " + roomId); }); }); } var test = io.sockets.on("connection", function(socket) { console.log("I'm in global connection handler"); socket.on("req_create_room", function(data) { if (roomIds.indexOf(data.roomId) == -1 ) { roomIds.push(data.roomId); update_listeners(data.roomId); } test.emit("room_created", {ok:true}); }); socket.on("disconnect", function(s) { console.log("Disconnected from global handler"); }); });
Keep in mind that the problem of creating connections before listeners are defined will still occur.