Problem Overview
WebSockets provide a full-duplex communication channel over a single TCP connection, making them ideal for real-time applications like chat apps, gaming, and live notifications. Here's how to implement WebSockets in a Node.js application:
- Step 1: Install the
ws
library using npm:
npm install ws
- Step 2: Set up a basic WebSocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log('Received: %s', message);
// Echo back the message to the client
ws.send(`Server: ${message}`);
});
});
console.log('WebSocket server is running on ws://localhost:8080');
- Step 3: Connect to the WebSocket server from the client:
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
socket.send('Hello, Server!');
};
socket.onmessage = (event) => {
console.log('Message from server:', event.data);
};
This setup will allow your Node.js application to communicate in real-time with connected clients. Remember to handle errors and disconnections appropriately to ensure a robust implementation.