Junior — Middle
Have you had experience using the WebSocket protocol in your projects?
sobes.tech AI
Answer from AI
Yes, I have experience using the WebSocket protocol in Node.js projects to implement bidirectional communication between the client and server in real time. For example, I have created chat applications and notification systems.
To work with WebSocket in Node.js, the ws library is often used.
Here's an example of a simple WebSocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
// Send the message back to the client
ws.send(`Echo: ${message}`);
});
ws.send('Welcome to the WebSocket server!');
});
WebSocket allows maintaining a persistent connection, which is useful for applications with real-time updates.