事件发射器模式如何在 Node 和 sockets.io 中工作? [英] how does event emitter pattern work in Node , sockets.io?

查看:46
本文介绍了事件发射器模式如何在 Node 和 sockets.io 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 node,阅读node.js in action这本书,我遇到了这段要在服务器端编写的代码.

I am trying to get my hands on node ,reading through the book node.js in action ,I am came across this bit of code which is to be written on server side.

var socketio = require('socket.io');
socket.on('rooms', function() {
socket.emit('rooms', io.sockets.manager.rooms);
});

我不确定这是如何工作的.据我了解,方法 socket.on() 注册/添加一个事件侦听器来侦听 rooms 类型的事件,然后回调一个发出 的函数房间 事件..??它是这样工作的吗?它没有意义......套接字对象何时发出房间事件?

I am not sure how this works. As far as I understood the method socket.on() registers/adds an event listener to listen to events of type rooms and then callbacks a function which emits a rooms event..?? is that how it works? its not making sense... when does the socket object emits rooms event?

推荐答案

这是一个自定义事件,由对方触发.在这个服务器端示例中,服务器等待客户端发送 rooms 事件,并且在回调中它也响应 rooms 事件.客户端反过来也可以监听 rooms 事件.

This is a custom event, triggered by the other side. In this server side example, server waits for the client sends rooms event, and in the callback it responds with rooms event as well. Client in turn can also listen for rooms event.

您可以随意命名这些事件.不必将这两个事件都命名为 rooms.

You could name these events as you want. It is not necessary that both these events are named rooms.

这篇关于事件发射器模式如何在 Node 和 sockets.io 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆