Skip to the content
- Long-polling
- Let’s say you want to check automatically if there is a new comment to add it automatically at the bottom of an article.
- Long-polling means you would check every Х seconds if there is something new, with web-sockets comments can come in automatically as they are posted
- Websockets have two advantages.
- They have much less overhead, which results in a better network performance
- They allow the server to send data that the client hasn’t explicitly requested.
- The second one is the most important advantage.
- In AJAX, everything the server sends must be the response to a previous request by the client, and every request can only be answered once.
- But in many applications, especially multi-user applications, events happen on the server and these events must be pushed to the clients immediately.
- There are workarounds for that in AJAX, like delaying the answer to a request until there is something to report (long-polling), but these are quite dirty.
- That’s why there are WebSockets.
- With a WebSocket connection, the server can send messages to the clients when it wants and as often as it wants, without having to wait for a request from the client.
- But unfortunately, WebSockets also have disadvantages:
- They aren’t as well-supported by web development frameworks
- Not all web browsers support it
- but most desktop browsers already do
- Many proxies and reverse-proxies can’t relay WebSocket traffic
Usage
- Websockets are a powerful technology and could certainly cater to the limited use cases but there can be compatibility problems with older browsers and network intermediaries.
- In fact, some folks even recommend having an HTTP fallback in case Websockets isn’t supported.
- Unless you have requirements that necessitate WebSockets, such as full-duplex bi-directional communications, for example, you might be better off using existing AJAX-based solutions.
- If you have requirements to push notifications to your user interface, WebSockets can be a good idea, but if you are literally looking for form submission and auto-complete, then these problems have already been solved using Ajax