WebSocket library in TypeScript: ws, Socket.IO and SockJS

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 library TypeScript: a complete overview for an educational website



WebSocket is a protocol that enables two-way real-time communication between a client and a server. In the TypeScript ecosystem, there are several popular libraries that simplify working with WebSocket. In this article, we will look at three main tools: ws, Socket.IO, and SockJS, and show how to integrate them into an educational project in TypeScript.



Why is WebSocket important for education?

Educational websites often require real-time features: chats, collaborative code editing, notifications, live streams. WebSocket eliminates the need for constant server polling and ensures instant data transfer. TypeScript adds typing, which is critical for maintaining large projects.



1. The ws library — a minimalist WebSocket for Node.js

ws is the simplest and fastest WebSocket library for the Node.js server side. It is perfect for cases where you need a pure WebSocket without additional features.



Installation

npm install wsnpm install @types/ws --save-dev


Server example in TypeScript

import { WebSocketServer } from 'ws';

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

wss.on('connection', (ws) => { console.log('New connection');

ws.send('Welcome to the educational website!');

ws.on('message', (data) => { console.log(`Received: ${data}`); ws.send(`Echo: ${data}`); });

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

console.log('WebSocket server started on ws://localhost:8080');


Client example in TypeScript

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

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

ws.onmessage = (event) => { console.log('Message from server:', event.data);};

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


Pros: minimal size, high performance, full control.
Cons: no automatic reconnection, no room support.



2. Socket.IO — a powerful library for real-time applications

Socket.IO is the de facto standard for real-time applications. It provides automatic reconnection, rooms, namespaces, and fallback transport support (e.g., long polling).



Installation

npm install socket.io socket.io-clientnpm install @types/socket.io --save-dev


Server example in TypeScript

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);

socket.on('join_room', (roomName: string) => { socket.join(roomName); socket.to(roomName).emit('user_joined', socket.id); });

socket.on('send_message', (data: { room: string; message: string }) => { io.to(data.room).emit('new_message', { user: 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 example in TypeScript

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

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

socket.on('connect', () => { console.log('Connected to server, ID:', socket.id); socket.emit('join_room', 'javascript-lesson');});

socket.on('new_message', (data) => { console.log(`${data.user}: ${

Recommendations