【问题标题】:How to send two variables in one message using Socket.io?如何使用 Socket.io 在一条消息中发送两个变量?
【发布时间】:2014-01-05 02:40:53
【问题描述】:

我有一个客户端 ID 和用户名,我希望它们都通过套接字发送。

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

我试过这个,但它似乎不起作用

【问题讨论】:

    标签: javascript node.js express socket.io


    【解决方案1】:

    你可以试试这个

    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
    
     });
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

        在服务器端:

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

        在客户端:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-09
          • 2018-12-24
          • 2018-01-14
          • 2012-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多