Sockets.Io: Using Sockets In The Web

February 19, 2024

Overview

My experience with sockets in web apps was through the socket.io API that serves as a wrapper for web-sockets when they're available, but can also simulate socket behavior via http long polling and other tricks. The way the technology works is:

  • setup a socket server that you can bind either to a port of your choosing or to the same port where the web server is ran.
  • the server socket will be listening for new connections from clients.
  • on new connections there should be some sort of authentication where a socket id for the connected socket client is linked to a user in our applications logic
  • on every new connection a callback for handling events of that emitted to that socket is passed.
  • now the frontend can subscribe to events on the client socket and the backend can handle broadcasting of messages and what not.

Rooms

socket.io rooms are a concept for broadcasting of events to multiple sockets that are joined to a room, instead of emitting an event to certain socket, you can emit the event to the room which will then handle broadcasting. this can be especially useful when you want to broadcast information to all sockets bound to a specific user (multiple browsers/browser windows with same user authenticated).

Important Functions

socket.on("eventName", callback) allows us to subscribe to an event.

socket.off("eventName", callback allows us to unsubscribe from an event.

socket.emit("eventName", { ...obj }) allows us to emit an event and send certain data with it.

io.on("connection", (socket) => handleEvents(socket, io)) allows us to set handlers for a socket on connection.

io.to(X).emit( ... ) allows us to emit an event with a body to a specific socket or room.