WebSocket on TypeScript: creating real-time applications
Modern web applications require instant data exchange between client and server. The WebSocket protocol provides a persistent two-way connection, making it ideal for creating chats, notification systems, online games, and other real-time services. In this article, we will thoroughly examine how to work with WebSocket on TypeScript — from server setup to client implementation.
What is WebSocket and why is it needed?
WebSocket is a communication protocol that provides a full-duplex channel over a single TCP connection. Unlike traditional HTTP, where the client sends a request and waits for a response, WebSocket allows the server to independently initiate sending data to the client.
Main advantages of WebSocket:
- Persistent connection — no need to establish a new connection for each request
- Low latency — data is transmitted instantly without the overhead of HTTP headers
- Two-way communication — the server can send data without a request from the client
- Efficiency — less traffic compared to polling solutions
WebSocket is widely used in financial applications (stock quotes), social networks (likes, comments in real time), multiplayer games, monitoring systems, and IoT.
Setting up a WebSocket server on TypeScript
To create the server, we will use the popular library ws. Install it via npm:
npm init -y
npm install ws
npm install -D typescript @types/ws @types/node
npx tsc --init
Let's create a file server.ts:
import { WebSocketServer, WebSocket } from 'ws';
const PORT = 8080;
const wss = new WebSocketServer({ port: PORT });
interface CustomMessage {
type: string;
payload: any;
}
wss.on('connection', (ws: WebSocket) => {
console.log('New client connected');
// Send a welcome message
const welcomeMessage: CustomMessage = {
type: 'welcome',
payload: { message: 'Welcome to the server!' }
};
ws.send(JSON.stringify(welcomeMessage));
// Handle incoming messages
ws.on('message', (data: Buffer) => {
try {
const message: CustomMessage = JSON.parse(data.toString());
switch (message.type) {
case 'chat':
// Broadcast the message to all connected clients
broadcast(message, ws);
break;
case 'ping':
ws.send(JSON.stringify({ type: 'pong', payload: {} }));
break;
default:
console.log('Unknown message type:', message.type);
}
} catch (error) {
console.error('Error processing message:', error);
}
});
ws.on('close', () => {
console.log('Client disconnected');
});
ws.on('error', (error: Error) => {
console.error('WebSocket error:', error);
});
});
function broadcast(message: CustomMessage, sender: WebSocket) {
wss.clients.forEach((client) => {
if (client !== sender && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
}
console.log(`WebSocket server started on ws://localhost:${PORT}`);
Start the server with the command npx ts-node server.ts. The server will listen on port 8080 and handle incoming connections.
Creating a WebSocket client on TypeScript
The client part can be implemented both for the browser and for Node.js. Let's look at both options.
Browser client
Let's create a file client.ts for use in a web application:
class WebSocketClient {
private socket: WebSocket;
private url: string;
constructor(url: string) {
this.url = url;
this.socket = new WebSocke