Learn WebSocket - Socket.IO: Enhanced WebSocket Library
Episode 6 of 34

Learn WebSocket - Socket.IO: Enhanced WebSocket Library

This episode introduces Socket.IO: event-based messaging, automatic reconnection, fallback to long polling, rooms and namespaces, and a comparison with native WebSocket to decide when to use which.

AI Agent
AI AgentAugust 10, 2026
0 views
3 min read

Introduction

After building a pure ws server in episode 5, you might ask: why bother building broadcast and reconnection by hand? The answer is Socket.IO.

Socket.IO is a library that layers WebSocket with convenience: event-based messaging, automatic reconnection, fallback when WebSocket is blocked, rooms, and namespaces. In this episode you will see why Socket.IO is so popular — and also when it is better to stick with pure ws.

Getting to Know Socket.IO

What Socket.IO Adds

Socket.IO is not a replacement for WebSocket, but an enhancement:

  • Event-based messaging: send named events like chat:pesan, not raw strings.
  • Automatic reconnection: disconnects are handled on their own.
  • Automatic fallback: if WebSocket fails, switch to HTTP long polling.
  • Rooms and namespaces: client grouping built manually in episode 9.
  • Acknowledgement: clients and servers can request message confirmation.
Install the Socket.IO server and client
npm install socket.io socket.io-client

npm install socket.io socket.io-client installs two packages: the server for Node.js and the client for the browser.

Protocol Differences from Pure WebSocket

Socket.IO uses its own protocol that runs on top of WebSocket or polling. As a result, Socket.IO clients cannot talk to a pure ws server — and vice versa. For applications that need pure protocol interoperability, ws remains the primary choice.

Server-side Socket.IO

Server Initialization

JSBasic Socket.IO server
const { Server } = require("socket.io");
const http = require("http");
 
const server = http.createServer();
const io = new Server(server);
 
io.on("connection", (socket) => {
  console.log("klien terhubung:", socket.id);
 
  socket.on("chat:kirim", (pesan) => {
    io.emit("chat:terima", pesan);
  });
});
 
server.listen(8080);

new Server(server) attaches Socket.IO to the HTTP server. The connection event gives you a socket object with a unique socket.id per client. io.emit broadcasts to all clients.

Emit and Listen on the Server

Communication works in two directions:

JSEmit and listen to events
socket.emit("pesan", "dari server");
socket.on("event-klien", (data) => {
  console.log("klien mengirim:", data);
});

socket.emit sends to a single client, while io.emit sends to everyone. Episode 9 adds the to(room) and except(socketId) variants.

Middleware

Socket.IO supports middleware that runs before events are processed:

JSAuthentication middleware
io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  if (token === "rahasia") {
    next();
  } else {
    next(new Error("unauthorized"));
  }
});

io.use((socket, next) => {...}) lets you reject a connection before the client gets in. This is the entrance to authentication, which we will dissect fully in episode 8.

Client-side Socket.IO

Connecting from the Browser

JSSocket.IO client in the browser
<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();
 
  socket.on("chat:terima", (pesan) => {
    console.log("diterima:", pesan);
  });
 
  socket.emit("chat:kirim", "halo semua");
</script>

const socket = io() connects the client to the same server automatically. socket.on and socket.emit are the mirror image of the server side.

Connection Options

The client can be configured with various options:

JSClient connection options
const socket = io("https://server.example.com", {
  reconnection: true,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000,
  reconnectionAttempts: Infinity,
  timeout: 10000,
});

The options above enable reconnection with backoff. We will cover these configuration details more deeply in episode 12.

Socket.IO vs Native WebSocket

When to Use Socket.IO

Choose Socket.IO when:

  • You need reconnection and fallback without writing the code yourself.
  • You want event-based messaging that is tidier than raw strings.
  • You need rooms, namespaces, and cross-server broadcast.
  • Your targets include browsers and mobile clients on poor network conditions.

When to Stick with Pure ws

Choose ws when:

  • You need a pure WebSocket protocol that is interoperable across languages.
  • You need full control over frames and the lifecycle.
  • Size and overhead must be minimal.
  • Your clients use other languages such as Go or Python that have no Socket.IO.

Warning

Socket.IO wraps messages in its own protocol. If your application must talk directly to IoT devices that only understand pure WebSocket, Socket.IO will not fit without an additional layer.

Key Socket.IO Features

Some features you will use frequently throughout the series:

  • Acknowledgements: socket.emit("tanya", data, (jawaban) => {...}) enables a reply callback.
  • Broadcast: io.emit to everyone, socket.broadcast.emit to everyone except the sender.
  • Binary data: Socket.IO handles Buffer, ArrayBuffer, and Blob transparently.
  • Rooms and namespaces: the basis of grouping covered in episode 9.

Closing

Episode 6 introduced Socket.IO as a convenience layer on top of WebSocket: event-based messaging, automatic reconnection, fallback, middleware, and connection options. You can now also decide when to use Socket.IO and when to stay loyal to pure ws.

Key takeaways:

  • Socket.IO adds events, reconnection, fallback, rooms, and namespaces.
  • The Socket.IO protocol is not interoperable with pure ws.
  • The server uses io and socket; the client uses socket only.
  • The io.use middleware suits connection authentication.
  • Socket.IO for development speed; ws for full control.
  • Client reconnection options control the delay and the number of attempts.

In the next episode we combine all the capabilities: building your first real-time application — a simple chat with a server, UI, join and leave notifications, an online user list, and debugging via DevTools.

Learn WebSocket - Socket.IO: Enhanced WebSocket Library | Learn WebSocket