Socket.io Node.js如何将套接字发送给特定用户?

时间:2018-01-11 09:11:45

标签: node.js socket.io

我知道这个问题: Send message to specific client with socket.io and node.js

但是我尝试了那里的任何答案,我收到了下一个错误:

/Users/razbuchnik/node/routes/sockets.js:13
      io.to["1ZAJEIGhcMP2k6zqAAAA"].emit("socketFromServer", info);
                                    ^

TypeError: Cannot read property 'emit' of undefined
    at Socket.<anonymous> (/Users/razbuchnik/node/routes/sockets.js:13:37)
    at Socket.emit (events.js:159:13)
    at /Users/razbuchnik/node/node_modules/socket.io/lib/socket.js:513:12
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
[nodemon] app crashed - waiting for file changes before starting...

1 个答案:

答案 0 :(得分:1)

您可以使用io.to,但首先您必须按照文档中的规定加入会议室。详细了解https://socket.io/docs/rooms-and-namespaces/#joining-and-leaving

io.on('connection', function(socket){
  socket.join('some room');
});

然后才

io.to('some room').emit('some event');