WebSocket Libraries TypeScript: Complete Overview and Practical Examples
In modern web development, WebSocket technology has become the standard for creating real-time applications. Thanks to a persistent two-way connection between the client and server, WebSocket is ideal for chats, online games, stock traders, monitoring systems, and any other projects requiring instant data transfer. In this article, we will thoroughly examine three main WebSocket libraries for TypeScript: ws, Socket.IO, and uWebSockets.js, including their installation, configuration, and code examples.
1. ws Library — Lightweight and Fast WebSocket for Node.js
The ws library is the most popular and minimalistic implementation of the WebSocket protocol for Node.js. It does not add any extra abstractions, works directly with the native protocol, and provides maximum performance. TypeScript support is available through types that can be installed separately.
Installation
npm install wsnpm install -D @types/wsSimple Server Example in TypeScript
import { WebSocketServer, WebSocket } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws: WebSocket) => { console.log('Client connected');
ws.on('message', (message: Buffer) => { console.log('Received message:', message.toString()); // Send a response to all connected clients wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(`Echo: ${message.toString()}`); } }); });
ws.on('close', () => { console.log('Client disconnected'); });});
console.log('WebSocket server running on ws://localhost:8080');Client Code (Browser)
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);};Pros: minimal overhead, full control over the protocol, great for high-load systems.
Cons: no built-in support for rooms, automatic reconnection, or fallback to HTTP transport.
2. Socket.IO — Universal Solution with Rich API
Socket.IO is not just WebSocket, but a full-fledged framework for real-time communications. It uses WebSocket as the primary transport but automatically falls back to HTTP long-polling if WebSocket is unavailable (e.g., behind proxies or in older browsers). Socket.IO provides ready-made mechanisms: rooms, namespaces, automatic reconnection, message delivery acknowledgements, and much more.
Installation
npm install socket.io socket.io-clientnpm install -D @types/socket.ioServer Example with Rooms in TypeScript
import { Server, Socket } from 'socket.io';import http from 'http';
const server = http.createServer();const io = new Server(server, { cors: { origin: '*' }});
io.on('connection', (socket: Socket) => { console.log('User connected:', socket.id);
// Join a room socket.on('join_room', (roomName: string) => { socket.join(roomName); socket.to(roomName).emit('user_joined', socket.id); });
// Send a message to a room socket.on('room_message', (data: { room: string; message: string }) => { io.to(data.room).emit('new_message', { user: socket.id, text: data.message }); });
socket.on('disconnect', () => { console.log('User disconnected:', socket.id); });});
server.listen(3000, () => { console.log('Socket.IO server running on port