Sending message to specific client with socket.io and empty message queue

后端 未结 9 1911
误落风尘
误落风尘 2020-12-22 20:16

I´m going crazy with socket.io! Documentation is so bad it\'s simply not true.

I want to send a feedback to specific client over socket.io

My server side loo

相关标签:
9条回答
  • 2020-12-22 21:00

    to send a message to a specific client save every one that connects to the server in an Object.

    var socketio = require('socket.io');
    var clients = {};
    var io = socketio.listen(app);
    
    io.sockets.on('connection', function (socket) {
      clients[socket.id] = socket;
    });
    

    then you can later do something like this:

    var socket = clients[sId];
    socket.emit('show', {});
    
    0 讨论(0)
  • 2020-12-22 21:01

    A couple of ways to send feedback to a specific client over socket.io include:

    • As stated by pkyeck, save all clients to an Object, so you can send to these specific clients later in your route handlers, e.g.:

      var sessionsConnections = {};
      sio.on('connection', function (socket) {
        // do all the session stuff
        sessionsConnections[socket.handshake.sessionID] = socket;
      });
      
    • or, use socket.io's built in support for rooms - subscribe each client to a room on connection and send via this room within route handlers, e.g.:

      sio.on('connection', function (socket) {
        // do all the session stuff
        socket.join(socket.handshake.sessionID);
        // socket.io will leave the room upon disconnect
      });
      
      app.get('/', function (req, res) {
        sio.sockets.in(req.sessionID).send('Man, good to see you back!');
      });
      

    Acknowledgement:

    http://www.danielbaulig.de/socket-ioexpress/#comment-1158

    Note that both these example solutions assume that socket.io and express have been configured to use the same session store and hence refer to the same session objects. See the links above and below for more details on achieving this:

    https://github.com/LearnBoost/socket.io/wiki/Authorizing

    0 讨论(0)
  • 2020-12-22 21:02

    First of all, you cannot use socket.id on client side.

    And then change the line

    var socket = io.connect('http://localhost:80/socket.io/socket.io.js');

    to

    var socket = io.connect('http://localhost:80/');

    0 讨论(0)
提交回复
热议问题