How to Create a WebSocket Server in Node.js Easily
To create a WebSocket server in Node.js, use the
ws library by installing it with npm install ws. Then, create a server with new WebSocket.Server({ port }) and listen for connection events to handle client messages.Syntax
The basic syntax to create a WebSocket server in Node.js involves importing the ws library, creating a new server instance, and listening for client connections and messages.
const WebSocket = require('ws');- imports the WebSocket library.const wss = new WebSocket.Server({ port: 8080 });- creates a server listening on port 8080.wss.on('connection', callback)- listens for new client connections.ws.on('message', callback)- listens for messages from a connected client.
javascript
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { ws.on('message', (message) => { console.log(`Received message: ${message}`); }); ws.send('Hello! You are connected.'); });
Example
This example shows a complete WebSocket server that listens on port 8080, sends a welcome message to clients, and logs any messages received from them.
javascript
import WebSocket from 'ws'; const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { ws.send('Welcome to the WebSocket server!'); ws.on('message', (message) => { console.log(`Received: ${message}`); ws.send(`You said: ${message}`); }); }); console.log('WebSocket server is running on ws://localhost:8080');
Output
WebSocket server is running on ws://localhost:8080
Common Pitfalls
Common mistakes when creating a WebSocket server include:
- Not installing the
wspackage before running the server. - Forgetting to handle the
connectionevent, so clients cannot connect. - Not sending or responding to messages, which makes the connection seem inactive.
- Using the old
requiresyntax in ES module projects or vice versa.
Always ensure your server listens on a port and handles client messages properly.
javascript
/* Wrong: No connection event handler */ import WebSocket from 'ws'; const wss = new WebSocket.Server({ port: 8080 }); // No wss.on('connection') - clients cannot interact /* Right: Proper connection and message handling */ wss.on('connection', (ws) => { ws.on('message', (msg) => { ws.send(`Echo: ${msg}`); }); });
Quick Reference
Key points to remember when creating a WebSocket server in Node.js:
- Install
wswithnpm install ws. - Use
new WebSocket.Server({ port })to start the server. - Listen for
connectionevents to handle clients. - Use
ws.on('message')to receive messages. - Use
ws.send()to send messages to clients.
Key Takeaways
Use the ws library to create a WebSocket server easily in Node.js.
Always handle the connection event to interact with clients.
Listen for message events to receive data from clients.
Send messages back to clients using ws.send().
Install ws with npm before running your server code.