Node.js WebSocket is a protocol that enables two-way communication between client and server over a single, long-lived connection. It allows real-time data exchange between the client and server without the need for polling or continuous HTTP requests.
Node.js provides a built-in module called ws
that implements the WebSocket protocol on both the server and client side. With this module, you can easily create a WebSocket server that listens to incoming connections from clients and sends messages back and forth in real time.
Here’s an example of how to create a simple WebSocket server using Node.js:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected');
ws.on('message', function incoming(message) {
console.log(`Received message: ${message}`);
ws.send(`You said: ${message}`);
});
ws.on('close', function close() {
console.log('Client disconnected');
});
});
In this example, we create a new WebSocket.Server
instance on port 8080
. When a client connects to this server, the connection
event is emitted and we log a message to the console.
We also define two event listeners on the WebSocket
object (ws
) that represents the connection with the client. The first one listens for incoming messages from the client and logs them to the console, as well as sends back a response message using ws.send()
. The second one listens for when the connection with the client is closed and logs another message to the console.
Overall, Node.js WebSocket makes it easy to implement real-time communication between clients and servers in your web applications.