Sobes.tech
Junior

Describe several methods of communication between the server and the client.

sobes.tech AI

Answer from AI

  • REST (Representational State Transfer): The client sends requests (HTTP methods: GET, POST, PUT, DELETE) to server resources represented by URLs. The server responds with data (usually in JSON or XML). The state is not maintained between requests (stateless).

  • GraphQL: An alternative to REST. The client requests only the data it needs in a single request. The server responds strictly according to the request. It provides more efficient data transfer, especially for applications with complex data requirements.

  • WebSockets: A full-duplex connection between the client and server over a single TCP connection. Both parties can send data at any time without constantly opening/closing connections. Ideal for real-time applications (chats, online games).

    // Example client code for WebSocket
    const ws = new WebSocket('ws://localhost:8080');
    
    ws.onopen = () => {
      console.log('Connection established');
    };
    
    ws.onmessage = (event) => {
      console.log('Received message:', event.data);
    };
    
    ws.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
    
    ws.onclose = () => {
      console.log('Connection closed');
    };
    
    // Sending a message
    ws.send('Hello, server!');
    
  • Server-Sent Events (SSE): The server sends streaming updates to the client over a single HTTP connection. The client cannot send data to the server over this connection, only receive. Useful for unidirectional notifications (e.g., news feed updates).

    // Example client code for SSE
    const eventSource = new EventSource('/events');
    
    eventSource.onmessage = (event) => {
      console.log('Received event:', event.data);
    };
    
    eventSource.onerror = (error) => {
      console.error('SSE error:', error);
      eventSource.close();
    };
    
  • Polling: The client periodically sends requests to the server to check for updates. Simple but inefficient, as most requests may not contain new data.

  • Long Polling: The client sends a request, and the server holds the connection until new data appears or a timeout occurs. Once data is sent or timeout expires, the client immediately sends a new request. More efficient than regular polling but can still create load.

Comparison table:

Method Directionality Real-time Data Efficiency Basic Implementation Simplicity
REST Client -> Server Low High
GraphQL Client -> Server Low Medium
WebSockets Bidirectional High Medium
SSE Server -> Client High Medium
Polling Client -> Server (frequent) Low High
Long Polling Client -> Server (long) Medium Medium
Describe several methods of communication between the… - sobes.tech