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

How to access the target socket in a Socket.io handler

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

文档中有这个例子:

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

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

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

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

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

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);
  });
});

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

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);
});