I have encountered a problem where socket.emit will not send an array.
When the client receives it, it’s just completely empty.
Server side:
var connectedUserNames = new Array() ;
socket.on('USER_ONLINE', function(data){
connectedUserNames[socket.id] = data ;
console.log(data+' has connected.') ;
})
io.sockets.emit('CONNECTED_USERS', connectedUserNames);
Client side:
socket.on('CONNECTED_USERS', function(data){alert(data);
$('#connectedusers').attr('title', data) ;
})
Is this a bug with NodeJS? If so, how could I work around this?
Your order seems very off there. You emit
CONNECTED_USERSsomewhere outside yourUSER_ONLINEevent, so its most likely not filled with data. By the way, you declaring anArraybut you access it like a plain object. If you don’t need an indexed Array, you should just create a plainObjector use
Array.prototype.push, which is more convinient thereTry to pull this line
into your
USER_ONLINEevent and then make sure, your client actually fires that event at some point, so your server can react to that.