WebSockets are really just an extension of the socket idea. While HTTP was invented for the World Wide Web, and has been used by browsers since then, it had limitations. It was a particular protocol that worked in a particular way, and wasn’t well suited for every need. In particular was how HTTP handled connections. Whenever you made a request, say to download html, or an image, a port/socket was opened, data was transferred, and then it was closed.
The opening and closing creates overhead, and for certain applications, especially those that want rapid responses or real time interactions or display streams of data, this just doesn’t work.
The other limitation with HTTP was that it was a “pull” paradigm. The browser would request or pull information from servers, but the server couldn’t push data to the browser when it wanted to. This means that browsers would have to poll the server for new information by repeating requests every so many seconds or minutes to see if there was anything new. In the late 2000’s, a movement to add Sockets to browsers was mounting.
In 2011, the WebSocket was standardized, and this allowed people to use the WebSocket protocol, which was very flexible, for transferring data to and from servers from the browser, as well as Peer-to-Peer (P2P), or direct communication between browsers. Unlike HTTP, the socket that is connected to the server stays “open” for communication. That means data can be “pushed” to the browser in realtime on demand.
WebSocket is an extension of HTTP.
- WebSockets provides these benefits over HTTP:
- Persistent stateful connection for the duration of connection
- Low latency: near real-time communication between server/client due to no overhead of reestablishing connections for each request as HTTP requires.
- Full duplex: both server and client can send/receive simutaneously
- WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than the sharing the ports for legacy reasons (firewall/proxy penetration), there isn’t much of a common ground to combine them into one protocol.
But the new WebSocket feature allows the server to send data whenever it wants. This allows to implement browser-based games with a much lower latency and without having to use ugly hacks like AJAX long-polling or browser plugins.