Sobes.tech
Junior — Middle

What methods can be used to implement real-time interaction?

sobes.tech AI

Answer from AI

To implement real-time interaction in Node.js, several methods can be used:

  1. WebSocket — a bidirectional communication channel between the client and server, allowing data exchange without repeated HTTP requests.

  2. Server-Sent Events (SSE) — a one-way connection from the server to the client, suitable for streaming updates.

  3. Long Polling — the client sends a request, and the server keeps it open until data is available, after which the client immediately sends a new request.

  4. Libraries and frameworks — for example, Socket.IO, which simplifies working with WebSocket and automatically switches to other methods if necessary.

Example of using WebSocket with the ws library:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received: ${message}`);
    ws.send(`Echo: ${message}`);
  });
});