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:
-
WebSocket — a bidirectional communication channel between the client and server, allowing data exchange without repeated HTTP requests.
-
Server-Sent Events (SSE) — a one-way connection from the server to the client, suitable for streaming updates.
-
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.
-
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}`);
});
});