最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS Socket.IO won't pass array to client - Stack Overflow

programmeradmin4浏览0评论

I have encountered a problem where socket.emit will not send an array.

When the client receives it, it's just pletely 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?

I have encountered a problem where socket.emit will not send an array.

When the client receives it, it's just pletely 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?

Share Improve this question asked Sep 18, 2012 at 10:28 imperium2335imperium2335 24.2k38 gold badges117 silver badges194 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

Your order seems very off there. You emit CONNECTED_USERS somewhere outside your USER_ONLINE event, so its most likely not filled with data. By the way, you declaring an Array but you access it like a plain object. If you don't need an indexed Array, you should just create a plain Object

var connectedUserNames = {};

or use Array.prototype.push, which is more convinient there

connectedUserNames.push( data );

Try to pull this line

io.sockets.emit('CONNECTED_USERS', connectedUserNames);

into your USER_ONLINE event and then make sure, your client actually fires that event at some point, so your server can react to that.

发布评论

评论列表(0)

  1. 暂无评论