Similarity/Difference between SocketIO and EventEmitter in NodeJS

只愿长相守 提交于 2019-11-30 17:50:11

问题


I am little confuse between Socket.io and EventEmitter API in nodejs. Yes, I am quite new in event driven NodeJS programming. Is there any significant difference between this two ? or one have made over the other one ? are they designed to serve the same purpose or different ?
Any example/resource link, illustrating difference between them would be nice..


回答1:


You shouldn't compare the EventEmitter API and Socket.IO, as they are completely different things and are unrelated except for the fact that Socket.IO uses events, both on the server side and client side.

The EventEmitter API is used by anything that emits events, for example, a HTTP server, streams, file operations, etc. They are used like this:

var EventEmitter = require('events').EventEmitter;
// create a new instance
var em = new EventEmitter();

// attach a handler to an event named "event"
em.on('event', function() {
});

// fire the "event" event
em.emit('event');

Socket.IO on the other hand, is a library for cross-browser realtime data transport. It is used to send data from a client to a server, or from a server to a client.

// on the server side
var io = require('socket.io');
io.sockets.on('connection', function(socket) {
  socket.emit('event');
});

// on the client side
var socket = io.connect();
socket.emit('data');


来源:https://stackoverflow.com/questions/19174467/similarity-difference-between-socketio-and-eventemitter-in-nodejs

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