9

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..

Aman Gupta
  • 5,548
  • 10
  • 52
  • 88
  • 1
    Read more about asynchronous programming, `socket.io` uses `EventEmitter` for events `connection`,`disconnect`, etc.. don't compare class against package .. – Gntem Oct 04 '13 at 06:25
  • it mixes streams with events, http://stackoverflow.com/questions/16719282/how-does-socket-io-work – Gntem Oct 04 '13 at 06:36

1 Answers1

16

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');
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
  • Thanks buddy... as any doubt is always a doubt without sound knowledge.. I will get hands on over both. Can you suggest some good book or resource for socket.io, I need some more knowledge about it. – Aman Gupta Oct 04 '13 at 14:54
  • The documentation is the best place to look, as well as the [wiki](https://github.com/LearnBoost/socket.io/wiki) on their Github. – hexacyanide Oct 05 '13 at 16:11
  • 1
    Can we use EventEmitter to emit events from a Service (Microservice Architecture) and listen to that event from another Service using Socket.io? – Dheeraj Kumar Apr 23 '19 at 10:16
  • 1
    Answering the question of Dheeraj Kumar, as far as I understand it is not possible to use the EventEmitter between different services, since it is designed for component interaction, meaning that it will only work internally. – Jesus Soto Sep 14 '21 at 17:16
  • 1
    @DheerajKumar I am able to get it working across services via EventSource: https://developer.mozilla.org/en-US/docs/Web/API/EventSource – Sgnl Jul 22 '22 at 00:33
  • In the browser it is included but for nodejs you have to explicitly install it – Sgnl Jul 22 '22 at 00:39