Sobes.tech
Junior

Describe some ways of communication between a server and a client.

sobes.tech AI

Answer from AI

Polling. The client periodically sends requests to the server to check for updates. Simple, but inefficient for infrequent data changes and introduces latency.

Long Polling. The client sends a request, and the server keeps the connection open until new data appears or a timeout occurs. Improves responsiveness compared to regular polling.

WebSockets. A bidirectional persistent connection between the client and server. Ideal for real-time applications such as chats or online games. Less overhead compared to HTTP requests.

Server-Sent Events (SSE). A unidirectional connection from the server to the client. The server can send data streams to the client over an HTTP connection. Suitable for notifications or real-time updates when data only comes from the server.

Fetch API / XMLHttpRequest (XHR). Standard methods for performing asynchronous HTTP requests from the client to the server. Used for data retrieval (GET), data submission (POST, PUT, DELETE, etc.).

// Example using Fetch API
fetch('/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
// Example using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data', true);
xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.error('Request failed.  Returned status of ' + xhr.status);
  }
};
xhr.onerror = function() {
  console.error('There was a network error.');
};
xhr.send();

Comparison of some methods:

Method Direction Persistent connection Usage
Polling Client -> Server No Simple applications
Long Polling Client <-> Server Conditionally Improved responsiveness
WebSockets Client <-> Server Yes Real-time, chats, games
Server-Sent Events Server -> Client Yes Notifications, streaming data
Fetch/XHR Client -> Server No Standard client requests