Sobes.tech
Junior — Middle

Have you worked with WebSocket protocol for implementing bidirectional communication in applications?

sobes.tech AI

Answer from AI

Yes, WebSocket is a protocol that provides a bidirectional, persistent connection between a client and a server over a single TCP connection. In Node.js applications, it is often used for implementing chats, games, notifications, and other scenarios where real-time data transfer is important.

Example of using WebSocket in Node.js with the ws library:

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 message back to client
    ws.send(`Echo: ${message}`);
  });

  ws.send('Welcome!');
});

Thus, WebSocket allows the server and client to exchange messages in real-time without the need for repeated HTTP requests.