how does event emitter pattern work in Node , sockets.io?

我的梦境 提交于 2019-12-12 02:52:11

问题


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

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?


回答1:


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.

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



来源:https://stackoverflow.com/questions/36553889/how-does-event-emitter-pattern-work-in-node-sockets-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!