Socket.io:如何处理服务器上的所有传入消息?
我希望能够在单个处理程序中处理来自客户端的所有消息。
示例客户端代码:
var socket = io.connect('http://localhost');
socket.emit('news', { hello: 'test' });
socket.emit('chat', { hello: 'test' });
示例服务器代码:
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
console.log(data);
}); });
我希望能够记录每条消息,即使它是通过新闻、聊天或任何其他名称发送的。这可能吗?
注意:上面的服务器代码不起作用。当前没有记录任何内容。我只是想知道是否有一个事件可以处理每个发出名称的所有消息。
I want to be able to handle all messages that are coming in from clients in a single handler.
Example client code:
var socket = io.connect('http://localhost');
socket.emit('news', { hello: 'test' });
socket.emit('chat', { hello: 'test' });
Example server code:
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
console.log(data);
}); });
I'd like to be able to log every message even if its sent on news, chat or whatever other name using emit. Is this possible?
Note: The above server code does not work. There is nothing currently logged. I am just wondering if there is a single event which could be handled for all messages for every emit name.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可以通过重写 socket.$emit 函数来实现
That is possible by overriding socket.$emit function
在 Socket.Io >3 上使用 < code>socket.onAny(listener):
从 Socket-io 2.0.4 开始就支持这种方式,你只需要注册一个中间件(来源自 socketio-wildcard):
It's even easier on Socket.Io >3 using the
socket.onAny(listener)
:This is supported out of the box now as of Socket-io 2.0.4, you simply need to register a middle ware (source from socketio-wildcard):
这是 Socket.IO 的未解决的问题。
这个时候,如果你真的需要它,你可能就得fork Socket.IO了。请参阅 3rd-Edens 评论 了解如何操作。
This is an open issue with Socket.IO.
At this time, if you really need it, you will probably have to fork Socket.IO. See 3rd-Edens comment for how to do it.