I'm creating a nodejs server for Unity3D, using socketio for the networking. I have a function that serves as match room and I want to leave that function when the player leaves the game. Each time the player creates a new room it should enter the function and start over. Is it possible to break execution of parent function from a child callback?
exports.initGame = function (userdata) {
//do prematch stuff with userdata and execute game logic on the callbaks
socket.on("something", function (someNetdata)({
// how do i stop parent function from here?
});
// more socket.on callbacks
}
EDIT: Forgot to mention that the function is being exported. Don't know if that change anything.
EDIT2: Given the suggestions discussed in jfriend00 answer, I'll give a more extended explanation of the problem.
The current flow is as it follows:
user connects and I define some functions on the Io "connected" callback. Relevant one is startMatchMaker(Io, socket, data)
. The matchMaker creates a room for the player (or joins one if there is one available) and proceed to executing the gameInit(io, socket, room, data)
mentioned before.
The gameInit(...)
function stores relevant data on global arrays with the room as key, for example, Players[room] = {/* player object */}
. The match is 1 vs 1, so when one player abandons the game, I remove the entries from the arrays, referring that room: delete Players[room]
. When the player moves, I update the player position on their object inside the global array. this is done on a callback, added inside the gameInit(...)
socket.on("move", function(data){
//do movement logic and update player position, if it is valid. Omitting the rest of the code.
Players[room].position = data.position;
});
Now lets imagine two players, player1 and player2 playing in room1. Player2 abandon the game by exiting the server. Player1 is still connected, but must leave that current game. All the variables are deleted (as mentioned before) and player1 joins a new game in room2. When player1 tries to move, 2 callbacks will be called: the one that was added in the first initGame with room = "room1"
and another added upon execution of the second match: room = "room2"
. A exception is thrown because there is no entry in Players with key = room1
.
Given this the solution is to remove the listeners from the previous match.