如何在 Socket.io 处理程序中访问目标套接字

Nic*_*dis 2 sockets node.js socket.io

我正在使用 Socket.io 服务器,并尝试访问从客户端发出事件的套接字。

文档中有这个例子:

socket.on('private message', function (from, msg) 
{
    console.log('I received a private message by ', from, ' saying ', msg);   
});
Run Code Online (Sandbox Code Playgroud)

尝试使用它时,我注意到最新版本中的参数顺序发生了变化,并且“from”参数实际上是一个函数。

我无法使用它来获取有关谁发出事件的信息。

还有别的办法吗?或者也许是使用参数来获取信息的方法?

jfr*_*d00 5

在服务器上,您的代码应该位于这样的闭包中,并且您可以访问包含套接字的父函数参数:

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {

    // you can access the argument socket from the parent function
    console.log(socket);
    // access the socket id of this socket
    console.log(socket.id);

    console.log(data);
  });
});
Run Code Online (Sandbox Code Playgroud)

如果要使用命名处理函数,可以创建一个存根函数,将套接字传递给命名处理函数,如下所示:

function myEventHandler(socket, data) {
    // you can access the argument socket from the parent function
    console.log(socket);
    // access the socket id of this socket
    console.log(socket.id);
    console.log(data);
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    myEventHandler(socket, data);
});
Run Code Online (Sandbox Code Playgroud)