Websocket

Event Emitter

An event emitter is a pattern that allows listening to a named event with callbacks (listeners), and when someone emits that event with a value, the callbacks will be fired and have the value as the arguments. Sometimes this is referred to as a “pub/sub” model, or listener. It's referring to the same thing.


Simple Implementation

In NodeJS, EventEmitter is a built-in class in events module, so you just need to import and use it like this:

import { EventEmitter } from 'events'

const emitter = new EventEmitter()

Or if you want to create your own EventEmitter you can check the below example for a simple implementation

class EventEmitter {
  constuctor() {
    this.events = {}
  }

  // or you can called this subcribe
  on(eventName, listener) {  
    this.events[eventName] = this.events[eventName] || []
    this.events[eventName].push(listener)
  }

  emit(eventName, ...args) {
    (this.events[eventName] || []).forEach((fn) => {
      fn(...args)
    })
  }

  off(eventName, listener) {
    this.events[eventName] = this.events[eventName] || []
    this.events[eventName] = this.events[eventName].filter(fn => fn !== listener)
  }
}

Basic Usage

Below is a simple example to show you how to use the EventEmitter

const emitter = new EventEmitter()
emitter.on("log", (data) => {
console.log(`Hello ${data} 1`)
})
emitter.on("log", (data) => {
console.log(`Hello ${data} 2`)
})
emitter.emit("log", "world")

Native WebSocket Event Emitter

Native WebSocket both the client and the server only support 4 basic events with no customization:

  • open: triggered when the connection between the client and the server established
  • message: triggered when the WebSocket receives messages sent by the server
  • close: triggered when the connection is closed either by the client or the server
  • error: triggered when there are some errors

Socket.io Event Emitter

Socket.io also has EventEmitter implemented, but Socket.io EventEmitter is a little different version because events emitting are happening through the connection between the client and the server. When an event is emitted on the client or the server, it will not trigger the listeners on its side, but instead, it will send a message and tell the other side to trigger their own listeners. For example, if the client emits an event called data, the server will receive a message and trigger data event listeners on its side and vice versa.

Unlike Native WebSocket, Socket.io is event-based so you can define and use any event names in Socket.io. Socket.io has only 3 built-in events besides message but with different names called connected, disconnected and connect_error. Other than that, you can define and use any event names you want to exchange messages between the client and the server, this also enables you to use different events for different purposes instead of just using the message event.

Previous
Socket.io