admin管理员组

文章数量:1173638

I have a clientid and username and i want them both send with the socket.

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

i tried this for example but it doesn't seem to work

I have a clientid and username and i want them both send with the socket.

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

i tried this for example but it doesn't seem to work

Share Improve this question edited Dec 17, 2013 at 12:01 Paul Mougel 17k6 gold badges58 silver badges65 bronze badges asked Dec 17, 2013 at 11:02 JulienJulien 2371 gold badge3 silver badges11 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 26

You can try this

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

and on the client

 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

 });

Try sending the object as a whole:

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

You should pass an object to socket event.

In server-side:

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

In client-side:

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

本文标签: javascriptHow to send two variables in one message using SocketioStack Overflow