How do we choose between the two?

Sometimes, when information is ready, we need to get it from the server. The AJAX request/response pattern we typically use does not keep the request connection established for this type of application. Instead, we need a push-based approach, such as WebSockets Protocol, long polling, server push events (SSE), and more recently HTTP2 server push. In this article, we will compare two approaches: WebSockets and long polling.

Overview of long polling

In 1995, Netscape hired Brendan Eich to implement scripting capabilities for Netscape Navigator, and in 10 days JavaScript was born. As a programming language, JavaScript was born at that time with very limited capabilities compared to modern JavaScript languages, and its interaction with the browser document Object Model (DOM) was even more limited. JavaScript is primarily used to provide limited enhancements to enrich the usability of browser documents. For example, validate forms in a browser and easily insert dynamic HTML into existing documents.Who is stronger? WebSockets and long polling to find out

As the browser wars heated up and Microsoft’s Internet Explorer reached version 4 and above, the battle for the browser’s powerful feature set led Microsoft to introduce a new feature in Internet Explorer, This feature eventually became XMLHttpRequest. XMLHttpRequest has been universally supported in all browsers for more than a decade.

Long polling is essentially a more efficient form of the original polling technique. Sending repeated requests to the server is a waste of resources because a connection must be established for each new incoming request, the HTTP header of the request must be parsed, a query for new data must be performed, and a response must be generated and delivered (usually without new data). You must then close the connection and clean up all resources. Long polling is a technique in which the server chooses to keep the client connection open for as long as possible, providing a response only after data becomes available or reaches a timeout threshold, rather than having each client make repeated requests several times before new data is available to the client.

Description of web sockets

Around the middle of 2008, developers Michael Carter and Ian Hickson became particularly acute about the pain and limitations of using Comet when implementing something truly robust. Working together on IRC and W3C mailing lists, they developed a plan to introduce a new standard for modern real-time two-way communication on the web, creating the name “WebSocket”.

The idea made its way into the W3C HTML draft standard, and shortly after, Michael Carter wrote an article introducing WebSockets in the Comet community. In 2010, Google’s Chrome 4 became the first browser to fully support WebSockets, and other browser vendors followed suit in the following years. In 2011, RFC 6455 — WebSocket protocol — was published on the IETF website.

In short, WebSockets are a transport layer built on top of the device’S TCP/IP protocol stack. The goal is to provide Web developers with a TCP communication layer that is as close to the original as possible in nature, while adding some abstractions to remove some of the drag from working on the Web. They also satisfy the fact that networks have additional security considerations that must be taken into account to protect consumers and service providers.

Advantages and disadvantages of long polling

advantages

Long polling, implemented after XMLHttpRequest, is almost universally supported by devices, so there is usually little need for further alternatives. However, in cases where exceptions must be handled, or where the server can query for new data but does not support long polling (not to mention other, more modern technical standards), basic polling is sometimes still useful, and simple HTML script tags can be leveraged using XMLHttpRequest or through JSONP.

disadvantages

Long polling takes up a lot of server resources. Reliable message ordering can be a problem with long polling because multiple HTTP requests from the same client can run simultaneously. For example, if a client has two browser tabs open, uses the same server resources, and the client application is persisting data to a local store (such as localStorage or IndexedDb), there is no guarantee that duplicate data will not be written multiple times. Depending on the server implementation, an acknowledgement of a message received by one client may also result in another client not receiving the expected message at all, because the server may mistakenly believe that the client has received the data it expected.

Advantages and disadvantages of WebSockets

advantages

WebSockets keep a unique connection open while eliminating long polling latency. WebSockets generally do not use XMLHttpRequest, so there is no need to send header data every time we need to fetch more information from the server. This, in turn, reduces the high cost of data loading when data is sent to the server.

disadvantages

WebSockets do not automatically restore connections when they are terminated – this is the part that you need to implement yourself, which is why there are so many client libraries. Browsers prior to 2011 cannot support WebSocket connections — but this is increasingly irrelevant. Why is the WebSocket protocol a better choice? In general, WebSockets are a better choice.

Long polling takes up more resources on the server, while WebSockets take up less space on the server. Long polling also requires multiple communications between the server and many devices. Different gateways have different criteria for how long a regular connection is allowed to remain open. If the connection is left open for too long, the process can be killed, even while the process is doing something important.

Reasons to build applications using WebSockets:

Full-duplex asynchronous messaging. In other words, both the client and the server can transmit messages to each other independently. WebSockets pass through most firewalls without any configuration. Good security mode (based on the original security mode). WebSockets Open Source Solution WebSocket library has two main categories: One implements only part of the protocol, leaving the rest to the developers, and the other builds on top of the protocol, with various additional features that real-time messaging applications typically require, such as recovery of lost connections, publish/subscribe channels, authentication, authorization, and so on.

The latter typically requires developers to use their own libraries on the client side, not just the original WebSocket API provided by the browser. Therefore, it is important to make sure that you are happy with the way your chosen solution works and the services it provides. Once you integrate your chosen solution into your architecture, you may find yourself stuck in the way the solution works, and any problems with reliability, performance, and scalability can come back to bite you.

Let’s start with the first category.

Note: All of the following are open source libraries.

ws

Ws is an “easy to use, fast, and fully tested WebSocket client and Node.js server.” It’s definitely a quasi-system-level implementation designed to do all the hard work of implementing the protocol, but the additional functions of restoring connections, publishing/subscribing, and so on, must be managed by you.

Client (browser before binding):

const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { ws.send('something'); }); ws.on('message', function incoming(data) { console.log(data); }); Server (node.js): const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); Mu web socketsCopy the code

μWS is a direct alternative to WS, with a particular focus on performance and stability. As far as I know, μWS is one step away from the fastest WebSocket server. That’s what drives SocketCluster, and I’ll talk about SocketCluster next.

There has been some controversy surrounding μWS recently due to the author’s attempt to extract it from NPM for philosophical reasons, but the latest working version of μWS is still on NPM and can be explicitly specified from NPM installation. That said, the authors are working on a new version, along with the node.js bindings that come with it.

var WebSocketServer = require('uws').Server;
var wss = new WebSocketServer({ port: 3000 });
function onMessage(message) {
    console.log('received: ' + message);
}
 
wss.on('connection', function(ws) {
    ws.on('message', onMessage);
    ws.send('something');
});
Copy the code

Client – Using WebSockets WebSocket API in browser defined by WHATWG HTML Living Standard is very simple to use. Building a WebSocket requires only one line of code:

JS

const ws = new WebSocket(‘ws://example.org’); Note that WS is used where HTTP schemes are normally used. Where HTTPS schemes are commonly used, WSS is also an option. These protocols were introduced along with the WebSocket specification to represent an HTTP connection that includes a request to upgrade the connection to use WebSockets.

Creating a WebSocket object by itself doesn’t do much. The connection is established asynchronously, so you must listen for the handshake to complete before sending any messages, and you need a listener to receive messages from the server:

Ws.addeventlistener ('open', () => {// Send a message to the WebSocket server ws.send('Hello! '); }); Ws. AddEventListener ('message', event => {// 'event' is a typical DOM event object, // The message data sent by the server is stored in the 'data' property console.log('Received:', event.data); });Copy the code

There are also error events and close events. WebSockets don’t automatically recover a connection when it terminates — you have to do it yourself, which is one of the reasons there are so many client libraries. While the WebSocket class is easy to use, it’s really just a basic building block. Support for different subprotocols or additional functionality, such as message transfer channels, must be implemented separately.

Long polling – Open source solutions Most libraries do not use long polling alone because long polling is often used in conjunction with, as an alternative to, or as an alternative to other transport policies when long polling does not work. Standalone long polling libraries are particularly rare in 2018 and beyond, and long polling is a technology that quickly loses relevance in the face of widespread transport support from more advanced alternatives. However, you can use it as a transport alternative. Here are some options for different languages:

Go: golongpoll PHP: php-long-polling Node.js: Pollymer Python: Relaxed Most relaxed client libraries use WebSockets to establish A real-time connection with relaxed. You then use simple HTTP requests for all other REST operations, including authentication.

However, the client library SDKS (such as our Javascript browser library) are designed to choose the available and best transport method based on the available browser and connection. By enabling additional transport options that fall back to the lowest common denominator, Relaxed ensures that almost all browsers can now connect to Relaxed in real time. Our Javascript browser library currently supports the following transports, in order of performance from best to worst:

WebSockets (supported by 94% of browsers worldwide as of December 2017) XHR stream XHR polling JSONP polling When implementing WebSocket support and using long polling as an alternative, Need to involve many aspects, not only relates to the client and server implementation details, but also support for other transport, to ensure the reliable support for different client environments, also involves a wider range of concerns, such as authentication and authorization, guaranteed message delivery, reliable message sorting, history, and more.

Resources and extended reading

Long polling

WebSockets

How does he work