Building a Scalable Chat Application with TypeScript and WebSocket
Learn how to build a simple and scalable chat application using TypeScript and WebSocket. This beginner-friendly tutorial covers setting up the server and client for real-time messaging.
Real-time messaging is a key feature of many applications today. Building a scalable chat application might seem complex at first, but using TypeScript and WebSocket makes the process straightforward and enjoyable. In this tutorial, we will create a simple chat server and a client using TypeScript, focusing on core concepts to help you understand how WebSocket works in practice.
WebSocket is a protocol that allows full-duplex communication channels over a single TCP connection. Unlike HTTP, where the client requests and the server responds, WebSocket enables both sides to send messages independently in real-time. This is perfect for chat apps.
Let's start by building the WebSocket server.
import WebSocket, { WebSocketServer } from 'ws';
const PORT = 8080;
const wss = new WebSocketServer({ port: PORT });
// Store all connected clients
const clients = new Set<WebSocket>();
wss.on('connection', (ws) => {
clients.add(ws);
console.log('New client connected');
// Listen for incoming messages
ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast message to all other clients
clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message.toString());
}
});
});
// Handle client disconnect
ws.on('close', () => {
clients.delete(ws);
console.log('Client disconnected');
});
});
console.log(`WebSocket server running on ws://localhost:${PORT}`);In this server code, we create a WebSocket server that listens on port 8080. We keep track of all connected clients using a Set. When a client sends a message, the server broadcasts it to all other connected clients, enabling group chat functionality.
Now, let's build the client side using the browser's native WebSocket API.
// client.ts
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Connected to chat server');
};
ws.onmessage = (event) => {
const message = event.data;
console.log('New message:', message);
// Here you could update your UI to display the message
};
ws.onclose = () => {
console.log('Disconnected from chat server');
};
// Function to send a chat message
function sendMessage(text: string) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(text);
} else {
console.log('Connection is not open');
}
}
// Example usage: send a message after connecting
setTimeout(() => {
sendMessage('Hello from client!');
}, 1000);This simple client connects to the WebSocket server and listens for messages. The sendMessage function allows you to send messages to the server, which then distributes them to other clients. You can expand this client by adding a user interface with HTML and CSS.
To run the server, save it as server.ts, install the 'ws' package via npm (`npm install ws`), and compile it with TypeScript or run it directly with ts-node. For the client, you can include the code in a TypeScript-enabled web project or compile it to JavaScript for use in a browser.
This setup provides the foundation for a scalable chat application. You can further enhance scalability by deploying the server with load balancers, using Redis or another message queue to synchronize clients across multiple server instances, or adding authentication for secure communication.
With this knowledge, you now know how to create a real-time chat app using TypeScript and WebSockets. Happy coding!