Websockets were designed for fast bi-directional communication in the browser. Assuming you have control over the server and a native client (say an iOS or Mac app), are there any good reasons or situations to communicate over a websocket instead of using an HTTP library?
Avoid using WebSockets if only a small number of messages will be sent or if the messaging is very infrequent. Unless the client must quickly receive or act upon updates, maintaining the open connection may be an unnecessary waste of resources.
§WS and WSS URL Schemes The primary use case for the WebSocket protocol is to provide an optimized, bi-directional communication channel between applications running in the browser and the server. However, the WebSocket wire protocol can be used outside the browser and could be negotiated via a non-HTTP exchange.
Whereas HTTP relies on a client request to receive a response from the server for every exchange, WebSockets allow for full-duplex bidirectional communication. This enables the server to send real-time updates asynchronously, without requiring the client to submit a request each time.
WebSockets were invented by developers to effectively facilitate real-time results. WebSockets work by initiating continuous, full-duplex communication between a client and server. This reduces unnecessary network traffic, as data can immediately travel both ways through a single open connection.
I'm going to answer a couple of different questions that hopefully ends up answering your question:
Is there a reason to use WebSockets from a client rather than HTTP? Yes.
WebSockets is bi-directional, full-duplex, low-latency and low-overhead compared to HTTP.
Part of the lower latency and overhead compared to HTTP/AJAX/COMET is that you don't have to re-establish the connection for each request.
Is there a reason to use WebSockets from a client rather than raw sockets? Yes.
The initial WebSockets handshake is HTTP server friendly (and has some origin and hash exchange safety mechanisms). It allows web servers to easily be updated to support redirect or proxy for WebSockets connections to the real WebSockets server application.
Another benefit of WebSockets is that it is a framed protocol which allows the application to focus on useful functionality without having to deal with its own framing and buffering.
Its fairly easy to add WebSockets support to existing TCP socket servers or proxy via something like websockify. Disclaimer: I made websockify.
From a server perspective WebSockets is a win because they can be accessed via standalone clients or via browsers. This means there are going to be more and more services that are currently TCP socket based that will be exposed via WebSockets. So adding WebSockets support to a client now will pay off in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With