So I wanted to build a little game app with socket.io, it works like that:
User loads a website and I create a general socket using generalConnection namespace
app.generalSocket = io.connect('http://localhost/generalConnection'); I don't have any special events on it yet, but I thought it would be nice to keep it separate from a second namespace.
When the user logs in I call a function that starts game connection (another namespace) and bind some events to it, I won't list them all, I think it's not important.
app.startGameSocket = function() { app.gameSocket = io.connect('http://localhost/gameConnection'); //game connection app.gameSocket.on("connect", function() { console.log("connected to the game socket"); }); } On the server side I have something like that:
var connectedPlayers = []; var gameConnection = io.of('/gameConnection').on('connection', function (socket) { socket.on('disconnect', function () { //some stuff }); }); Once again, I don't think I need to list all the events, I'll just explain how it works.
It listens to new player event, creates new player, pushes it connectedPlayers array and then sends it to everybody who is connected to gameConnection namespace.
User list is updated and everybody's happy. I can also listen to other events like disconnect and update the connectedPlayers array appropriately when user closes the browser window.
I also had to disconnect the gameConnection namespace when users log outs from the game, so on the client side I do:
app.vent.on('logOut', function() { app.gameSocket.disconnect(); )}; Notice that I keep generalConnection namespace open, I just disconnect the gameConnection namespace.
It works nice, if user logouts or closes window, disconnect event is triggered on the server side, connectedPlayers array is updated and sent back to connected players.
The problem
When user:
- Enters website.
- Logs in to the game.
- Logs out.
- Logs in again without refreshing window (triggers app.startGameSocket function again).
- And after all that closes the window, the gameConnection namespace disconnect event is not triggered on the server and list is not updated.
Node shell says stuff like: info - transport end (socket end) but not triggers the disconnect event. Please help :)
I tried to
app.vent.on('logOut', function() { app.gameSocket.emit('forceDisconnect'); //force disconnect on the server side app.gameSocket.disconnect(); app.gameSocket.removeAllListeners(); //tried to really kill disconnected socket )}; But no results.