Websockets provide real-time, full-duplex communication between a client and server on a single long-lived connection.
Here’s a basic implementation process with a popular library called `ws`:
1. Add `ws` Module: The first step is adding the Websockets library to your project. If you haven’t installed it yet, you can install it via npm using the following command:
\`\`\` npm install ws \`\`\`1. Setup a WebSocket Server: To configure WebSocket in Node.js, import the ws module and call its Server constructor function:
\`\`\`javascript const WebSocket = require(‘ws’); const wss = new WebSocket.Server({ port: 8080 }); console.log(‘WebSocket server is waiting for connections…’); \`\`\`In this case, you have created a WebSocket server that listens on port 8080 and is preparing for incoming connections.
1. Process WebSocket Messages: The server needs to respond to incoming messages. It’s now time to set up event handlers for connection and message events:
\`\`\`javascript wss.on(‘connection’, (ws) => { ws.on(‘message’, (message) => { console.log(‘Received message => ‘, message) ws.send(‘Hello! Message received.’); }); ws.send(‘Welcome! You have connected successfully!’) }); \`\`\`So, when a client connects, the server sends them a welcome message. Then, whenever it gets a message from the client, it responds to acknowledge receipt.
1. Testing the WebSocket server: To test the WebSocket server, you can use a WebSocket client. An example is to create a HTML file with JavaScript code to open a WebSocket connection and send/receive messages. Here it is:
\`\`\`html \`\`\` Now, you can use various form of clients includes console, mobile devices or web browsers to interact with the WebSocket server. After a connection is established, a client can send a message, and the server will respond to the message.