Monday 10 April 2017

Socket.io client doesn't receive messages, but it can send them

From what i can tell the client can send messages to the server just fine, and the server is receiving them fine too. The problem seems to be when the server is sending a message or when the client tries to receive them.
I suspect it is the client that is the problem as in addition to not receiving messages I get this whenever i do a socket.emit of any kind:
Chrome dev-tools console output
I have tried the same cdn for socket.io-client as I did in my last project and the script from the node module. No luck with any of them.

Here is the server and client code ( full code on my git ):

Server

/*
 * Server side
 */

module.exports = function(server){

var io = require('socket.io')(server);

[ . . . ] ( SOCKET_LIST, CLIENT_LIST and client() function is here)

io.on('connection', function(socket) {

  // On Connection
  console.log('Socket connected | ID: ' + socket.id);

  SOCKET_LIST[socket.id] = socket;
  CLIENT_LIST[socket.id] = client();

  socket.emit('welcome', {msg: 'Hey!'});


  socket.on('hasPlayer', function(data) {
    [ . . . ]
  });


  socket.on('userCreate', function(data) {

    // Make sure socket has unique id
    var newid = game.newId(); // creates a unused alphanumerical id
    while(game.players[newid] != null) {
      newid = game.newId();
    }

    // try creating the user. return bool if successful inform user of userId
    if( game.newPlayer(newid, data.name) ) { // returns true if player-name is available 

      socket.emit('userCreate', {status: true, id: newid});
      console.log('Socket ' + socket.id + ' created user: (' + newid + ')' + data.name);

    } else {

      socket.emit('userCreate', {status: false, msg: 'Username allready in use.'});
      console.log('User creation failed');

    }
  });

  // disconnect client
  socket.on('disconnect', function() {

    console.log('Socket disconnected | ID: ' + socket.id);
    delete SOCKET_LIST[socket.id];
    delete CLIENT_LIST[socket.id];

  });

});

[ . . . ]

} // ### Module export END

Client

/*
 * Client side
 */

var socket = io();

socket.on('hasPlayer', function(data) {
  console.log(data);
});

socket.on('userCreate', function(data) {
  console.log(data);
});

socket.on('welcome', function(data) {
  console.log(data);
});

As you can see you should get a 'welcome' message when you connect however it doesn't show up in the console.
And from the console of the server everything seems to be working there.

I've done two other applications like this now and I've had no issues. And comparing the code from these previous projects there are no real differences that should have this impact.

Chances are I've been looking at this for too long and just can't see what's right in front of me but hopefully some of you can see what I'm missing.
In advance thanks!



via Otard95

No comments:

Post a Comment