Search code examples
webwebsocketclientpollingweb-development-server

Connections in polling and web sockets


I am fairly new to the web development and confused about some concepts. Specifically, I am not sure what is the difference between long polling and web sockets.

Does long polling involve initiating a new TCP connection to the server for each request or is there a persistent TCP connection over which polling is done? If I understood it right, I think WebSockets allow the persistent TCP connection where data is exchanged between server and client and the duration of this connection is mentioned in the headers.

Any comments/help would be appreciated.


Solution

  • Long polling is where the client sends an http request to the server. If the server has data available for the request, it returns that data immediately as the http response and that connection is done.

    If the server doesn't have any data immediately, then it hangs onto the connection for some period of time (designed to be less than a typical client timeout). If data arrives before the time limit, then the http response is sent with the data and the connection is done.

    If new data does not become available in the server before the time limit expires, then the server returns a response that it has no data yet and that http socket is done. At that point, the client issues a new request on a new socket and starts the whole process over again.

    Does long polling involve initiating a new TCP connection to the server for each request or is there a persistent TCP connection over which polling is done?

    New connection each time. This is why polling is not particularly efficient.

    If I understood it right, I think WebSockets allow the persistent TCP connection where data is exchanged between server and client and the duration of this connection is mentioned in the headers.

    A webSocket is designed to be a persistent connection that can last a really long time and then data can be sent by either client or server at any time. A webSocket connection has additional setup compared to an http request, but can be a ton more efficient vs. long polling once it is established.

    More info explained in these references:

    websocket vs rest API for real time data?

    Long-polling vs websocket when expecting one-time response from server-side

    HTML5 WebSocket: A Quantum Leap in Scalability for the Web