WebSockets is a communication protocol that enables two-way communication between a client and a server over a single, long-lived connection. Unlike the traditional request-response model of HTTP, the WebSocket protocol provides full-duplex communication, allowing messages to be sent simultaneously in both directions. This bidirectional communication greatly reduces the latency and overhead associated with opening and closing multiple connections, making it particularly suitable for real-time applications, such as chat applications, online gaming, and live data feeds.
To use WebSockets in a Node.js application, you first need to install the ‘ws‘ package, which provides a simple WebSocket server and client. To install the package, run the following command:
npm install ws
Once you have the package installed, you can create a simple WebSocket server as follows:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
console.log('Client connected');
// Listen for messages from the client
socket.on('message', (message) => {
console.log(`Received: ${message}`);
// Echo the message back to the client
socket.send(`You sent: ${message}`);
});
// Listen for the socket to close
socket.on('close', () => {
console.log('Client disconnected');
});
});
This example creates a simple WebSocket server that listens for incoming connections on port 8080. When a client connects, it logs a message, and sets up listeners for the ‘’message’‘ and ‘’close’‘ events from the connected client. When the server receives a message from the client, it echoes the message back to the client.
To connect to the WebSocket server from a client-side script, you can use the built-in ‘WebSocket‘ object in most modern web browsers:
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
console.log('Connected to server');
socket.send('Hello, server!');
});
socket.addEventListener('message', (event) => {
console.log(`Received: ${event.data}`);
});
socket.addEventListener('close', () => {
console.log('Disconnected from server');
});
This client-side example connects to the WebSocket server and sends an initial message. It also sets up event listeners to handle messages from the server and the closing of the connection.
In summary, the WebSocket protocol enables two-way communication between a client and a server over a persistent connection, which is well-suited for real-time applications. Node.js applications can use packages like ‘ws‘ to create WebSocket servers and communicate with connected clients.