Sending a message to a client via its socket.id

前端 未结 2 980
清酒与你
清酒与你 2020-12-04 11:47

I can only seem emit messages to users when their socket id has been directly stored within the io.sockets.on(\'connect\') function. I don\'t know why it doesn\'t work when

2条回答
  •  感动是毒
    2020-12-04 12:17

    There are some problems with your code, the first being you shouldn't authenticate users through Socket.IO, you should make sure they can connect only after they authenticated. If you are using Express, then the following article can help you a lot: http://www.danielbaulig.de/socket-ioexpress/

    Also you should be avoiding sending messages like so, since that is part of Socket.IO internally and may change:

    io.sockets.socket(id).emit('hello');
    

    Instead (if you want to send a message to a specific client) it's better to keep an object for example with the connected clients (and remove the client once disconnected):

    // the clients hash stores the sockets
    // the users hash stores the username of the connected user and its socket.id
    io.sockets.on('connection', function (socket) {
      // get the handshake and the session object
      var hs = socket.handshake;
      users[hs.session.username] = socket.id; // connected user with its socket.id
      clients[socket.id] = socket; // add the client data to the hash
      ...
      socket.on('disconnect', function () {
        delete clients[socket.id]; // remove the client from the array
        delete users[hs.session.username]; // remove connected user & socket.id
      });
    }
    
    // we want at some point to send a message to user 'alex'
    if (users['alex']) {
      // we get the socket.id for the user alex
      // and with that we can sent him a message using his socket (stored in clients)
      clients[users['alex']].emit("Hello Alex, how've you been");
    }
    

    Sure, io.sockets.socket(id) may work (didn't actually test), but also it can be always changed as it's part of the Socket.IO internals, so my solution above is more 'safe'.

    Another thing you may want to change in your code on the client side is var socket = io.connect(''); with var socket = io.connect('http://localhost');, as we can see in the official example of Socket.IO here: http://socket.io/#how-to-use

提交回复
热议问题