WebSocket on TypeScript: Advanced Techniques for Real-Time Applications

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 on TypeScript: Advanced Techniques for Real-Time Applications



WebSocket provides a persistent bidirectional connection between client and server, making it ideal for real-time applications: chats, notifications, collaborative editing, and online games. In this article, we will explore advanced techniques for working with WebSocket on TypeScript, going beyond a simple echo server.



1. Architecture with Room Management (Rooms)



In real applications, global broadcasting to all clients is rarely used. Much more often, logical separation of clients into rooms is required (e.g., chat rooms or game sessions). Let's look at an implementation in TypeScript using the ws library.



import { WebSocketServer, WebSocket } from 'ws';

interface Room { id: string; clients: Set<WebSocket>;}

class RoomManager { private rooms: Map<string, Room> = new Map();

createRoom(roomId: string): void { if (!this.rooms.has(roomId)) { this.rooms.set(roomId, { id: roomId, clients: new Set() }); } }

joinRoom(roomId: string, client: WebSocket): void { this.createRoom(roomId); this.rooms.get(roomId)!.clients.add(client); client.send(JSON.stringify({ type: 'room_joined', roomId })); }

leaveRoom(roomId: string, client: WebSocket): void { const room = this.rooms.get(roomId); if (room) { room.clients.delete(client); if (room.clients.size === 0) { this.rooms.delete(roomId); } } }

broadcastToRoom(roomId: string, message: object, sender?: WebSocket): void { const room = this.rooms.get(roomId); if (room) { const data = JSON.stringify(message); room.clients.forEach(client => { if (client.readyState === WebSocket.OPEN && client !== sender) { client.send(data); } }); } }}

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

wss.on('connection', (ws: WebSocket) => { ws.on('message', (raw: Buffer) => { try { const msg = JSON.parse(raw.toString()); switch (msg.type) { case 'join': roomManager.joinRoom(msg.roomId, ws); break; case 'leave': roomManager.leaveRoom(msg.roomId, ws); break; case 'message': roomManager.broadcastToRoom(msg.roomId, { type: 'chat', user: msg.user, text: msg.text }, ws); break; } } catch (e) { ws.send(JSON.stringify({ type: 'error', message: 'Invalid JSON' })); } });

ws.on('close', () => { // Cleanup: remove client from all rooms roomManager.leaveRoom('*', ws); });});


This code demonstrates safe room management: on-demand creation, automatic cleanup of empty rooms, and excluding the sender from the broadcast.



2. Authentication and State Management



WebSocket connections must be authenticated. An advanced approach is token verification at connection establishment and session maintenance.



import { IncomingMessage } from 'http';import { WebSocketServer, WebSocket } from 'ws';

interface AuthenticatedSocket extends WebSocket { userId?: string; username?: string;}

const wss = new WebSocketServer({ port: 8080, verifyClient: (info: { req: IncomingMessage }, callback: (res: boolean) => void) => { const token = extractToken(info.req.url || ''); if (token && validateToken(token)) { callback(true); } else { callback(false); } }});

function extractToken(url: string): string | null { const params = new URLSearchParams(url.split('?')[1] || ''); return params.get('token');}

function validateToken(token: string): boolean { // Here should be actual JWT or other token validation return token.length > 10;}

wss.on('co

Blogs

Book Recommendations