简体   繁体   English

如何检测未注册的socket.io事件?

[英]how to detect socket.io event which is not registered?

I'm using node.js and socket.io for a chat program and I listen to some events.我将 node.js 和 socket.io 用于聊天程序,并监听一些事件。 Here is the relevant code:这是相关的代码:

server: io.sockets.on('connection',( socket ) => {
    socket.on('joinRoom',( data )=>{ do with message });
    socket.on('leaveRoom',( data )=>{ do with message });
}
client: io.emit('joinRoom',{uid:11});

If the client emits an event which is not registered as io.emit('noEvent',{});如果客户端发出未注册为io.emit('noEvent',{}); , how does the server detect it? ,服务器如何检测?

Use socketio-wildcard plugin.使用socketio-wildcard插件。

You can use the wildcard plugin for socket IO to do that as suggested in SocketIO official documentation here , like so:您可以按照 SocketIO 官方文档here 中的建议使用套接字 IO 的通配符插件来执行此操作,如下所示:

socket.on('*', function(packet){
  // client.emit('foo', 'bar', 'baz')
  packet.data === ['foo', 'bar', 'baz']
});

Because the socket server is listening for something to happen on the port not the 'event'.因为套接字服务器正在侦听端口上发生的事情,而不是“事件”。 So if something is 'emitted' and there is a 'listener' it will pick that up, it just won't know exactly what to do with it.因此,如果某些东西被“发射”并且有一个“监听器”,它会接收到它,它只是不知道如何处理它。

Not sure if this will help but here is the socket.io cheetsheet不确定这是否有帮助,但这里是 socket.io cheetsheet

In 3.x, it can be done without any plugins using onAny listener :在 3.x 中,它可以在没有任何插件的情况下使用onAny listener 完成

socket.onAny((eventName, ...args) => {
  const isNotRegistered = !Object.keys(socket._events).includes(eventName)
  
  if (isNotRegistered) {
    // Event is not registered
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM