// Import 'ws' module
const WebSocket = require('ws');
// Create WebSocket Server on port 8080
const wss = new WebSocket.Server({ port: 8080 });
// Event listener for new connections
wss.on('connection', (ws) => {
// Event listener for incoming messages
ws.on('message', (message) => {
console.log('Received:', message);
// Send a response back to the client
ws.send('Server: ' + message);
});
});
code
Simple WebSocket Server using 'ws' library
This Node.js code sets up a simple WebSocket server using the 'ws' library. It listens for connections, logs received messages, and responds to clients. The comments provide explanations for each part of the code.
Node.js
WebSocket
ws library
Server
Communication