0

I have the following code:

function Socket(io, playGame, mapper) {
    io.on('connection', function (socket) {
        // message handler for the chat message
        socket.on('sendChat', function (data) {
            console.log(socket);
            console.log(data);
            console.log('recieved chat');

            var connectedPlayer = playGame.findConnectedPlayer(socket);
            if (!connectedPlayer)
                return;

            var connectedGame = playGame.findConnectedGame(socket, connectedPlayer.gameId);
            if (!connectedGame)
                return;

            // send update game with players properly ordered
            for (socketIndex in this.sockets) {
                var socket = this.sockets[socketIndex];

                // send the new data to each player
                socket.socket.emit('chatUpdate', { chatText: data.chat });
            }
        });

        // message handler for join game message
        socket.on('joinGame', function (data) {
            console.log('recieved join:', JSON.stringify(data));

            if (!playGame.newConnectedPlayer(socket, data))
                return;

...

In the method for sendChat, socket is undefined. In the method for joinGame, socket is defined. I have tried several ideas, but the problem persists. Any help would be appreciated.

1 Answers1

0

You'll have to rename one of the 2 socket variables -- either the parameter for 'connection' or the var in the loop:

io.on('connection', function (socket) {
for (socketIndex in this.sockets) {
    var socket = this.sockets[socketIndex];

The var is shadowing the parameter, rendering the parameter inaccessible.

This happens in part because the var socket doesn't only exist within the for loop. JavaScript vars are function-scoped and their declarations are hoisted to the top of the function, as in:

socket.on('sendChat', function (data) {
    var connectedPlayer, connectedGame, socket; // each initially `undefined`

    console.log(socket);

    // ...

    for (socketIndex in this.sockets) {
        socket = this.sockets[socketIndex];

    // ...
});

And, having the same exact name, at most only one of them can be reached from a particular function.


Also note that the for loop and var socket aren't really necessary.

You can use the Socket.IO Server's own .emit() method to send a message to all clients.

io.emit('chatUpdate', { chatText: data.chat });
Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199