Why to use websocket and what is the advantage of using it?

JR Sahoo.'JS' picture JR Sahoo.'JS' · Jul 4, 2017 · Viewed 15.2k times · Source

I tried reading some articles, but not so clear on this topic.

Would someone like to explain me below points:

  • Why use websocket over http
  • what is full duplex communication
  • what do you mean by lower latency interaction

Answer

jfriend00 picture jfriend00 · Jul 4, 2017

Why use websocket over http?

A webSocket is a continuous connection between client and server. That continuous connection allows the following:

  1. Data can be sent from server to client at any time, without the client even requesting it. This is often called server-push and is very valuable for applications where the client needs to know fairly quickly when something happens on the server (like a new chat messages has been received or a new price has been udpated). A client cannot be pushed data over http. The client would have to regularly poll by making an http request every few seconds in order to get timely new data. Client polling is not efficient.

  2. Data can be sent either way very efficiently. Because the connection is already established and a webSocket data frame is very efficiently organized, one can send data a lot more efficiently that via an HTTP request that necessarily contains headers, cookies, etc...

what is full duplex communication?

Full duplex means that data can be sent either way on the connection at any time.

what do you mean by lower latency interaction

Low latency means that there is very little delay between the time you request something and the time you get a response. As it applies to webSockets, it just means that data can be sent quicker (particularly over slow links) because the connection has already been established so no extra packet roundtrips are required to establish the TCP connection.

For a comparison in what's involved to send some data via an http request vs. an already established webSocket connection see the steps listed in this answer: websocket vs rest API for real time data?

These other references may also be useful:

Server-push whenever a function is called: Ajax or WebSockets

Push notification | is websocket mandatory?

HTML5 WebSocket: A Quantum Leap in Scalability for the Web