Client and Server communicate through the HTTP, which is on the Application Layer.

  • HTTP Request/Response:
    • Client sends the requests to servers that are independent of each other. It is like a coin toss. The toss is independent of the last outcome.
    • This method is insufficient to load dynamic data on a web page. Each update will require a page refresh.
  • Ajax Request:
    • Asynchronous send data to the server without refreshing
    • Server keeps open the connection with the client. The client is the one that always initiates the request. The server can not proactively send resp
    • This method is insufficient when we are designing applications like Facebook feed. Users will have to manually send requests to ask for an updated feed as the server can not send the response proactively.
  • WebSockets:
    • full-duplex bi-directional communication
    • It is an upgrade over HTTP
      • Uses the same TCP connection over ws:// or wss:///
    • Sends headers only once
  • Polling and Long Polling
    • Polling: Sends Ajax request every X amount of seconds for new data
    • Long Polling: Client sends a request to the server and keeps connection open until new data

WebSocket

const socket = new WebSocket('ws://localhost:8000');

socket.onopen = (event) => {
    //on connection, do something
    console.log('Socket open');
});

socket.onmessage = (event) => {
    //message from server
    console.log(event.data);
});


References

  1. FreeCodeCamp
  2. Gojek Link 1 Link 2