Setting Up WebSocket Server with Node.js
Setting Up a WebSocket Server with Node.js
WebSockets provide a full-duplex communication channel over a single TCP connection, making them ideal for real-time applications like chat apps, live notifications, or gaming.
In this article, we’ll cover the steps to set up a WebSocket server using Node.js.
1. Prerequisites
- Node.js: Ensure you have Node.js installed. Download Node.js
- Text Editor: Use any text editor or IDE like VS Code.
2. Install the Required Dependencies
For handling WebSocket connections, we’ll use the ws
library. It is lightweight and widely used.
Run the following command in your project directory:
npm install ws
3. Creating a Basic WebSocket Server
Step 1: Initialize the Project
Create a new directory and initialize a Node.js project:
mkdir websocket-server
cd websocket-server
npm init -y
Step 2: Write the WebSocket Server Code
Create a file named server.js
and add the following code:
const WebSocket = require('ws');
// Create a WebSocket server
const wss = new WebSocket.Server({ port: 8080 });
console.log("WebSocket server is running on ws://localhost:8080");
// Handle connection events
wss.on('connection', (ws) => {
console.log('A new client connected.');
// Send a welcome message to the client
ws.send('Welcome to the WebSocket server!');
// Handle incoming messages from the client
ws.on('message', (message) => {
console.log(`Received: ${message}`);
ws.send(`Echo: ${message}`);
});
// Handle client disconnection
ws.on('close', () => {
console.log('A client disconnected.');
});
});
This script creates a WebSocket server listening on port 8080
, handles client connections, and echoes received messages.
4. Running the Server
Start the WebSocket server:
node server.js
You should see:
WebSocket server is running on ws://localhost:8080
5. Testing the WebSocket Server
Option 1: Using WebSocket Client in Browser
You can test the WebSocket server directly in your browser console:
- Open a browser.
- Go to the developer tools console.
- Type the following code to connect to the server:
const socket = new WebSocket('ws://localhost:8080'); // Log messages from the server socket.onmessage = (event) => { console.log('Server:', event.data); }; // Send a message to the server socket.onopen = () => { socket.send('Hello, Server!'); };
- You’ll see the server echo the message back.
Option 2: Using WebSocket Tools
You can also use tools like:
6. Adding Advanced Features
Enhance your WebSocket server with features such as:
- Broadcast Messages:
wss.on('connection', (ws) => { ws.on('message', (message) => { // Broadcast the message to all connected clients wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(message); } }); }); });
- Authentication: Use tokens or other mechanisms to validate clients.
- Secure WebSocket (WSS): Use HTTPS with SSL certificates for encrypted connections.
7. Closing the Server Gracefully
To handle server shutdown properly:
process.on('SIGINT', () => {
console.log('Shutting down the server...');
wss.close(() => {
console.log('WebSocket server closed.');
process.exit(0);
});
});
8. Next Steps
Explore WebSocket use cases:
- Build a real-time chat application.
- Create a dashboard for live data updates.
- Implement multiplayer games.
By following this guide, you’ve created a fully functional WebSocket server using Node.js. With further customization, you can build robust real-time applications!