Working with WebSockets in Node.js using TypeScript

WebSockets enable full-duplex communication between a server and client, making them ideal for building real-time applications. This guide will provide a step-by-step process for setting up a WebSocket server using Node.js and TypeScript.

Prerequisites

  • Basic knowledge of TypeScript and Node.js
  • Node.js installed
  • A package manager (like npm or yarn)

1. Setting up the Project

First, let's create a new directory for our project and initialize a new Node.js project:

mkdir websocket-ts cd websocket-ts npm init -y

Now, let's install and configure TypeScript:

npm install typescript --save-dev npx tsc --init

This will create a tsconfig.json file. You can adjust the compiler options based on your needs, but for this guide, the defaults should be sufficient.

2. Installing Required Packages

We'll be using the ws library for handling WebSocket connections. To install it and its type definitions:

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

3. Creating the WebSocket Server

Create a new file called server.ts.

import WebSocket, { Server } from 'ws'; import http from 'http'; const PORT = 8080; // Create an HTTP server const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('WebSocket server running'); }); // Create a WebSocket server by passing the HTTP server instance to ws const wss = new Server({ server }); console.log(`WebSocket server started on port ${PORT}`);

4. Handling Client Connections

Extend the code in server.ts to handle client connections, messages, and disconnections.

wss.on('connection', (ws: WebSocket) => { console.log('Client connected'); // Handle messages from clients ws.on('message', (message: string) => { console.log(`Received message: ${message}`); }); // Handle client disconnect ws.on('close', () => { console.log('Client disconnected'); }); });

5. Running the Server

With everything set up, we just need to start our HTTP server. Add the following code at the end of server.ts:

server.listen(PORT, () => { console.log(`HTTP server started on port ${PORT}`); });

To run your WebSocket server, compile the TypeScript code and then start the server:

npx tsc server.ts node server.js

Your WebSocket server should now be running on http://localhost:8080/. Clients can connect to it and start sending and receiving real-time messages.

Invite only

We're building the next generation of data visualization.