如何使用Socket.io在一条消息中发送两个variables?

我有一个clientid和用户名,我希望他们都与套接字发送。

client.userid = userid; client.username = username; client.emit('onconnected', { id: client.userid, name: client.username }); 

我试过这个例子,但它似乎并没有工作

你可以试试这个

 io.sockets.on('connection', function (socket) { socket.on('event_name', function(data) { // you can try one of these three options // this is used to send to all connecting sockets io.sockets.emit('eventToClient', { id: userid, name: username }); // this is used to send to all connecting sockets except the sending one socket.broadcast.emit('eventToClient',{ id: userid, name: username }); // this is used to the sending one socket.emit('eventToClient',{ id: userid, name: username }); } } 

并在客户端

  socket.on('eventToClient',function(data) { // do something with data var id = data.id var name = data.username }); 

尝试发送整个对象:

 $('form').submit(function(){ var loginDetails={ userid : userid, username : username }; client.emit('sentMsg',loginDetails); }