The ws library helps you create a WebSocket server easily. It lets your server and clients talk in real-time, like a chat app.
0
0
ws library for WebSocket server in Node.js
Introduction
You want to build a chat app where messages appear instantly.
You need a live game server that updates players quickly.
You want to show live notifications or updates on a website.
You want to connect a dashboard to live data from a server.
Syntax
Node.js
import WebSocket, { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function message(data) { console.log('received: %s', data); }); ws.send('Hello! Message from server'); });
Use WebSocketServer to create the server on a port.
Listen for connection events to handle new clients.
Examples
Creates a WebSocket server listening on port 3000.
Node.js
const wss = new WebSocketServer({ port: 3000 });Sends a welcome message to each new client that connects.
Node.js
wss.on('connection', ws => { ws.send('Welcome!'); });
Logs any message received from a client.
Node.js
ws.on('message', message => { console.log('Client says:', message); });
Sample Program
This code creates a WebSocket server on port 8080. When a client connects, it logs a message and sends a greeting. When the client sends a message, the server logs it and replies back with confirmation.
Node.js
import WebSocket, { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', ws => { console.log('New client connected'); ws.on('message', message => { console.log(`Received from client: ${message}`); ws.send(`Server got your message: ${message}`); }); ws.send('Hello! You are connected to the server.'); });
OutputSuccess
Important Notes
Make sure the port you choose is open and not used by other apps.
Clients must use WebSocket protocol to connect (ws:// or wss://).
Use ws.send() to send messages to clients.
Summary
The ws library makes real-time communication easy.
Create a server with WebSocketServer and listen for connections.
Send and receive messages using ws.send() and message events.