0

I'm trying to make a little party system just for practice with sockets, I've come into a snag, basically my methodology for this party system will just be

On page load, ask for username, populate all clients with new username which is an anchor with the id of their username, when anchor is clicked, send the specific client a request to invite them to a party.

I've almost gotten to the part with sending the link, so far I have:

socket.on('adduser', function(username) {
  socket.username = username;
  socket.clientId = socket.id;
  usernames[username] = username;
  console.log(socket.id);
  socket.emit('updatechat', 'SERVER', 'You have connected.');
  io.sockets.emit('updateusers', usernames);
  console.log(usernames);
});

for creating new users and

socket.on('updateusers', function(data) {
  var users = document.getElementById('users');
  users.innerHTML = '';
  for (var key in data) {
    var a = document.createElement('a');
        a.id = key;
        a.href='#';
        a.innerHTML = key;
    users.appendChild(a);
    users.appendChild(document.createElement('br'));
    document.getElementById(key).addEventListener('click', function() { 
      inviteUser.call(this); 
    });
  }
});

for the client side

I'm just getting confused on how to send the emit to a specific user instead of to everybody,

normally I would socket.emit to send an emit to the user that requested the whatever, but now I need to send to somebody else

I was thinking of storing a socket.id into an object and sending the request to the id that matches the username, but how can I emit to a specific ID?

TL;DR: How can I send an emit to a specific socket.id so only they get the request.

Thanks guys :)

4

1 回答 1

-1

好吧,您必须为此抓住客户,您可以采用简单的方式:

var io = io.listen(server);

io.clients[sessionID].send();

这可能会破坏,我几乎不怀疑,但 io.clients 总是有可能被改变,所以请谨慎使用上述内容

或者您自己跟踪客户端,因此您在连接侦听器中将它们添加到您自己的客户端对象中,并在断开连接侦听器中删除它们。

于 2013-05-13T18:31:14.370 回答