WebSocket Libraries TypeScript: ws and Socket.IO – Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

WebSocket Libraries TypeScript: ws and Socket.IO



WebSocket is a protocol that provides two-way real-time communication between a client and a server. In the TypeScript/Node.js ecosystem, the most popular libraries for working with WebSocket are ws (lightweight) and Socket.IO (with additional features). In this article, we will take a detailed look at both libraries, their installation, basic usage, and code examples in TypeScript.



1. The ws Library



ws is a minimalistic and fast WebSocket library for Node.js, fully compatible with TypeScript. It provides a clean WebSocket API without unnecessary abstractions.



Installation

npm install wsnpm install -D @types/ws


Creating a WebSocket Server in TypeScript

import { WebSocketServer, WebSocket } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws: WebSocket) => { console.log('Client connected');

// Sending a message to the client ws.send('Welcome!');

// Handling incoming messages ws.on('message', (data: Buffer) => { const message = data.toString(); console.log(`Received: ${message}`);

// Sending a response to all connected clients wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(`Echo: ${message}`); } }); });

// Handling connection close ws.on('close', () => { console.log('Client disconnected'); });});

console.log('WebSocket server started on port 8080');


Client Code in TypeScript

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => { console.log('Connection established'); ws.send('Hello, server!');};

ws.onmessage = (event: MessageEvent) => { console.log(`Response from server: ${event.data}`);};

ws.onclose = () => { console.log('Connection closed');};


2. The Socket.IO Library



Socket.IO is a higher-level library built on top of WebSocket. It adds:

  • Automatic reconnection on connection loss
  • Support for rooms and namespaces
  • A fallback mechanism (switching to HTTP long-polling if WebSocket is unavailable)
  • Built-in event support


Installation

npm install socket.io socket.io-clientnpm install -D @types/socket.io @types/socket.io-client


Server in TypeScript with Socket.IO

import { Server } from 'socket.io';import http from 'http';

const server = http.createServer();const io = new Server(server, { cors: { origin: '*', methods: ['GET', 'POST'] }});

io.on('connection', (socket) => { console.log(`User connected: ${socket.id}`);

// Joining a room socket.on('join_room', (room: string) => { socket.join(room); console.log(`Socket ${socket.id} joined room ${room}`); });

// Handling a custom event socket.on('chat_message', (data: { room: string; message: string }) => { // Sending a message to everyone in the room except the sender socket.to(data.room).emit('chat_message', { userId: socket.id, message: data.message }); });

socket.on('disconnect', () => { console.log(`User disconnected: ${socket.id}`); });});

server.listen(3000, () => { console.log('Socket.IO server started on port 3000');});


Client in TypeScript with Socket.IO

import { io, Socket } from 'socket.io-client';

const socket: Socket = io('http://localhost:3000');

socket.on('connect', () => { console.log('Connected to server');

// Join a room socket.emit('join_room', 'room_1');});

socket.on('chat_message', (data: { us

Recommendations