繁体   English   中英

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

[英]How to send two variables in one message using Socket.io?

我有一个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.name // here, it should be data.name instead of data.username

 });

尝试将对象作为整体发送:

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

您应该将对象传递给套接字事件。

在服务器端:

socket.emit('your-event', { name: 'Whatever', age: 18 })

在客户端:

socket.on('your-event', ({ name, age }) => {
    // name: Whatever
    // age: 18
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM