Websockets, Long-Polling, and Server-Sent Events

Sonya Vera
The Startup
Published in
4 min readSep 9, 2020

After building your first few full-stack web applications, you’re probably used to the pattern of request and response between the client and the server. The client asks the server for information, and if the server determines we are authorized to make the request and it knows how to fulfill it, it sends a response.

And the initial idea of the web was that it functions in this way: a one-way request from client to server; a connection that ends when the request is fulfilled.

But we know from our own use of the internet that data is often consumed by the client in a much more dynamic way.

After AJAX was introduced in 2005, developers start to explore ways to make the relationship between client and server bidirectional, so that servers could push data to the client without being prompted by an HTTP request for each batch of data. If client needs to fetch new data at a high frequency, making a bunch of HTTP requests would be inefficient because each time an HTTP request is sent, headers and cookie data are sent as well, which across a large number of requests can add up to quite a bit of data that needs to be transferred. This causes latency, which we know users do not appreciate. Furthermore, the client side would only know if there was new data available if it made a request.

So the industry needed solutions to enable a persistent, low latency connection that can support transactions initiated by the client or the server.

If we think about popular websites like Facebook or Twitter, we know that new data is rendered on the page without our having initiated a request for it on our side. On Facebook messenger, new messages appear on our screen without a refresh or any action taken on the client side. How does it work?

Long polling

One of the solutions for this problem is called long polling, which involves keeping an HTTP connection open until the server has data to push to the client. If when the request is made to the server there is no data available yet, the server prolongs the responds while the client waits.

If during this time new data becomes available, it is sent to the client. When data is sent or when the request times out — whichever happens first — a new request is made to reestablish the connection.

This creates the illusion of a server initiated connection, showing the user new information as it becomes available. This mechanism is used by gmail and Facebook, for example.

Server-side events

If data needs to flow consistently from the server to the client and not the other way around (think: news feeds), a developer might use the EventSource interface to allow for server-sent events. The following code would open a connection to the server to begin receiving events from it, with the URL of a script that generates the events.

const newEventSource = new EventSource("example.php")

This method has the benefit of having only one HTTP requests, and allows the client to receive events in text/event-stream format without closing the connection.

Websockets

When an application involves a functionality that depends on consistent real-time data from the server, a developer might consider using a Websocket which, after an initial HTTP request for an initial “handshake” to establish the connections, allows the server and the client to send messages to each other at any time without either party making a request.

Websockets essentially convert the HTTP connection to a Websocket connection. Websockets are a part of HTML5 and are supported by all modern browsers — in other words, there is a javascript API to use them natively in the browser. Unlike other mechanisms mentioned in this blog post, Websockets can detect a dropped or disconnected client and can also handle up to 1024 connections per browser.

The most common implementations for Websockets are voice/video chat, multiplayer games, instant chat app or push notifications.

Creating a WebSocket connection from the client side could be accomplished with the following code (with a real URL that used the WebSocket API):

// Create WebSocket connection.const socket = new WebSocket('example.com');// Connection openedsocket.addEventListener('open', function (event) {socket.send('Hello Server!');});// Listen for messagessocket.addEventListener('message', function (event) {console.log('Message from server ', event.data);});

Source: MDN web docs

There’s much more to these three mechanisms than what I’ve mentioned here, so I recommend to myself, my Flatiron cohort-mates, and fellow junior developers that we do what we do best and Google it to learn more. :)

--

--

Sonya Vera
The Startup

I’m a software engineering student at the Flatiron school in NYC.