Working with WebSockets in Node.js using TypeScript
November 6, 2023
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
You could ship faster.
Imagine the time you'd save if you never had to build another internal tool, write a SQL report, or manage another admin panel again. Basedash is built by internal tool builders, for internal tool builders. Our mission is to change the way developers work, so you can focus on building your product.
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.
TOC
November 6, 2023
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
You could ship faster.
Imagine the time you'd save if you never had to build another internal tool, write a SQL report, or manage another admin panel again. Basedash is built by internal tool builders, for internal tool builders. Our mission is to change the way developers work, so you can focus on building your product.
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.
November 6, 2023
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
You could ship faster.
Imagine the time you'd save if you never had to build another internal tool, write a SQL report, or manage another admin panel again. Basedash is built by internal tool builders, for internal tool builders. Our mission is to change the way developers work, so you can focus on building your product.
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.
What is Basedash?
What is Basedash?
What is Basedash?
Ship faster, worry less with Basedash
Ship faster, worry less with Basedash
You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.
You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.
You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.
Dashboards and charts
Edit data, create records, oversee how your product is running without the need to build or manage custom software.
USER CRM
ADMIN PANEL
SQL COMPOSER WITH AI
Related posts
Related posts
Related posts
How to turn webpages into editable canvases with a JavaScript bookmarklet
Kris Lachance
How to fix the "not all code paths return a value" issue in TypeScript
Kris Lachance
Type Annotations Can Only Be Used in TypeScript Files
Kris Lachance
Guide to TypeScript Recursive Type
Kris Lachance
How to Configure Knex.js with TypeScript
Kris Lachance
"No overload matches this call" in TypeScript
Kris Lachance