Why use websockets
As internet speeds increase, we expect our data in real time. To address this need, WebSocket, a popular communication protocol finalized in , enables websites to send and receive data without delay.
With WebSockets, you can build multiplayer games, chat apps, and collaboration software that work on the open web. I built several projects with WebSockets before I started to wonder what exactly was happening under the hood.
In this article, we will:. By the end of this piece, you should feel comfortable discussing how WebSockets work, and maybe even inspired to use it in your next project. The key word in that definition is two-way : with WebSocket, both the client and the server can trigger communication with one another, and both can send messages, at the same time. Why is this a big deal?
In a traditional HTTP system, which is used by the majority of websites today, a web server is designed to receive and respond to requests from clients via HTTP messages. This traditional communication can only be initiated in one direction: from the client to the server. Server code defines what type of requests the server should expect and how to respond to each of them. A common metaphor for this type of communication is a restaurant kitchen.
It goes something like this:. The important thing to note here is that the kitchen has no idea who the order is coming from. We do have ways around that—for example, clients can send along cookies that help the server identify the client, but the HTTP messages themselves are distinct and are read and fulfilled independently.
The kitchen has no concept of you —only the orders that come in. In server-speak, the only way for clients to get updated information from the server is to send requests. You send a message to the server, as a request with some text as a payload. The server receives your request and stores the message. As it stands, you and your friend—both clients—need to constantly check the server for updates, introducing awkward delays between every message.
Here it is! One dead simple solution to this problem is a technique called short polling. Just have the client ping the server repeatedly, say, every ms or over some fixed delay.
That way, you get new data every ms. Another workaround to the delay in receiving data is a technique called long polling. Long polling is more efficient than pinging the server repeatedly since it saves the hassle of parsing request headers, querying for new data, and sending often-empty responses.
However, the server must now keep track of multiple requests and their order. Also, requests can time out, and new requests need to be issued periodically. However, SSE is not supported by older browsers, and most browsers limit the number of SSE connections you can make at the same time.
So, we need a way to send information to the server, and receive updates from the server when updates come in. Enter WebSocket! Supported by almost all modern browsers , the WebSocket API allows us to open exactly that kind of two-way connection with the server. Moreover, the server can keep track of each client and push messages to a subset of clients.
With this capability we can invite all of our friends to our chat app and send messages to all of them, some of them, or only your best friend. So, how exactly does this magic work? In the last section, we mentioned HTTP several times. Very little non-payload data gets sent across the existing network connection this way, which helps to reduce latency and overhead, especially when compared to HTTP request and streaming models. Google Chrome was the first browser to include standard support for WebSockets in Before a client and server can exchange data, they must use the TCP Transport Control Protocol layer to establish the connection.
WebSockets effectively run as a transport layer over the TCP. During a new websocket handshake, the client and server also communicate which subprotocol will be used for their subsequent interactions. After this is established, the connection will be running on the WebSocket protocol.
Websockets are HTML5 compliant, and offer backwards compatibility with older html documents. A single server can have multiple WebSocket connections open simultaneously, and can even have multiple connections with the same client, which opens the door for scalability. There are many open-source resources and tutorials for incorporating WebSockets in an application, like the Javascript library Socket.
PubNub takes a protocol-agnostic stance, but in our current operations we have found that long polling is actually the best bet for most use cases. This is partly because of the maintenance and upkeep required to scale WebSockets, and potential issues that can arise when you can not easily identify a disconnection.
WebSockets are a great tool, but long polling works reliably in every situation. PubNub uses long polling to ensure reliability, security, and scalability in all networking environments, not just most. Long polling can be just as efficient as WebSockets in many real-word, real-time implementations. In fact, we have developed a method for efficient long polling — written in C and with multiple kernel optimizations for scale. PubNub is a real-time communications platform that provides the foundation for authentic virtual experiences, like live updates, in-app chat, push notifications, and more.
The building block structure of our platform allows for extra features like Presence, operational dashboards, or geolocation to be incorporated. Though they come with the overhead of having to re-authenticate and re-authorize the client on each request. And the server needs to implement some kind of event aggregation to overcome blackouts between re-connects. There are no JS APIs available for this mechanism, there is no re-connection handling, nor dropped client detection. When it comes to pushing data from the server to clients both WebSockets and Server-Sent Event will do the job.
There are some subtle differences and incompatibilities, but there are libraries that solve those issues. If you don't need to send data to the server in "real-time" e. They are the standard HTTP way of pushing data like notifications, messages or events to clients.
And they can be added just by implementing an additional endpoint in a controller , lowering the need to refactor the existing code base in a well structured code base the "implementation cost" of both WS and SSE is the same , and making them somewhat faster to implement and bring the feature to market.
I don't have experience with long polling on projects with large numbers of concurrent users, so I can't attest the claims I've read about it being the better solution for those kinds of applications. Though, while we were reverse engineering Facebook's Messenger to add PGP to it I noticed that they utilize long polling to fetch messages. On smaller projects I would recommend SSE over Long polling since it's easier to implement on both the server and client side.
All solutions are basically the same when it comes to pushing data from the server to clients. For a comparison in what's involved to send some data via an http request vs. Server-push whenever a function is called: Ajax or WebSockets. For a push notification, is a websocket mandatory? Stack Overflow for Teams — Collaborate and share knowledge with a private group.
Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Why to use websocket and what is the advantage of using it?
Asked 4 years, 4 months ago. Active 4 months ago. Viewed 17k times. Improve this question. Willi Mentzel
0コメント