An Introduction to WebSockets in JavaScript

WebSocket is a technology built into many modern web applications. If you write code for the web, you’ve probably heard this term before, but you might not be sure what it is or how to use it. Fortunately, WebSocket is not a complex concept and you can pick up a basic understanding of it fairly quickly.

What is WebSockets?

WebSocket, unfortunately, is one of those names that doesn’t seem to make sense at first glance. WebSocket is actually the name of a communication protocol that allows two-way communication between the client and the web server.

USE VIDEO OF THE DAY

In simpler terms, WebSocket is a technology that allows a client and a server to create a connection where either party can send a message to the other at any time.

This is different from a normal HTTP connection, where the client has to issue a request, and only then the server can send a response. In fact, WebSocket is a completely different communication protocol than HTTP which was designed to be HTTP compatible. When a client application wants to initiate a WebSocket connection, it must use the HTTP upgrade mechanism to switch to the WebSocket protocol.


At this point you might be thinking, “a protocol is just a set of rules, how can you use it to code?”.

The missing piece is what is called a protocol stack. Essentially, devices that support a protocol incorporate hardware and software that allow you to write applications that communicate using the protocol. The protocol is not directly used to build anything.

Why was WebSocket created?

To illustrate the need for WebSocket, consider the mechanism behind internet chat.

Someone sends a message to the chat server from their device, but the server still needs to send that message to your device before you can read it. If the server is using HTTP, the server can’t pass this message directly to you, because the server can’t initiate requests.

There are several ways to solve this problem with HTTP. One way is for the client to constantly send update requests to the server, and the server will pass whatever data it has in the response. This technique is called polling, and each request is called a poll. There are two polling variants: long polling and short polling.


Using the long polling variant means that the client device constantly asks the server if new messages are available. If new messages are available, the server will send the messages in response. Otherwise, the server would delay the response and hold the connection open until it had data to send back, then the client would immediately make a new request.

This technique is inefficient because HTTP was not designed to be used this way. It works fine on a small scale, but each HTTP request involves sending additional data in the header, which puts a huge load on the server when many clients are querying it.

Here is a diagram illustrating a long query:

The short query variant is even less efficient. In a short poll, the server does not keep the connection open until there is new data, which means that the client must continue to poll the server at fixed, very short intervals.

Another two-way communication technique in HTTP is called streaming.

In streaming, after the first request is sent, the server keeps the connection open indefinitely, sending new information as continuous partial responses to the client.

Using streaming incurs less data overhead and server load than polling because ideally the client only makes a single HTTP request. Unfortunately, streaming creates problems under certain conditions because browsers and network intermediaries (like proxies) often try to handle partial responses as chunks of a large HTTP response (which is normal HTTP behavior), instead of the separate posts they were intended for. be.

WebSocket was created to solve these problems. Unlike HTTP, WebSocket was designed specifically for two-way communication. With WebSocket, once a connection is opened, the client and server can send messages back and forth without the issues of polling or broadcasting.


Use cases for WebSocket

WebSocket is great, but that doesn’t mean it should be used everywhere.

Implementing WebSocket can add complexity to your application, especially on the server side, so it shouldn’t be done unless you have a good reason. This begs the question: what does a good reason look like?

WebSocket is ideal for use cases where frequent low latency two-way communication is required. In other words, WebSocket provides an advantage for applications that need to communicate frequently or at large scale. If the communication does not need to be real-time or the application will never scale to scale, polling or streaming may be sufficient for use in that application.

Typical uses of WebSocket are in creating chat applications, online multiplayer games, real-time collaboration and notification software, etc.

How to use client-side WebSocket

Using WebSocket on the server side can be quite complicated, and the process varies greatly depending on the language (like C#, Java, etc.) and library of choice, so we won’t cover that here. Next, we will briefly see how to use WebSocket on the client side.

All modern browsers implement a web API called WebSocket API, which is the browser’s protocol stack for the WebSocket protocol. You can use WebSocket in JavaScript using this API. The API allows you to create a WebSocket object, through which you create a WebSocket connection and interact with the WebSocket server.

You can use the following code format to create a WebSocket object:

let exampleSocket = new WebSocket("wss://www.example.com/socketserver", "dummyProtocol");

The first constructor argument is the URI of the WebSocket server you want to create a connection to. It will always start with “ws” or “wss”. The second argument is optional. Its value is either a string or an array of strings, which specifies the subprotocols you support.

The WebSocket object has a read-only property called readyState. Accessing this property provides the current state of the WebSocket connection. readyState has four possible values: “connecting”, “open”, “closing” and “closed”.

When this line of code runs, the browser tries to connect to the specified server. The connection will not be terminated immediately, so the readyState of exampleSocket will be “connecting”. No messages can be sent or received until the connection is terminated, at which time the value of readyState will change to “open”.


The exampleSocket The object has an event listener (which is different from DOM event listeners) called “onopen” which allows you to perform other actions only after the connection has been established. The object also has a “send” method which allows you to send Strings, Blobs (binary data) and ArrayBuffers as messages to the server.

Here is an example that uses them together:

exampleSocket.onopen = function (event) {
exampleSocket.send("WebSocket is really cool");
};

The API also allows you to react to messages sent by the server. This is done with the “onmessage” event listener. Here is an example :

exampleSocket.onmessage = function (event) {
console.log(event.data);
}

Instead, you can also write an arrow function:

exampleSocket.onmessage = (event) => { console.log(event.data); }

The API also provides a close() method to close the connection. Here’s what it looks like:

exampleSocket.close();

WebSocket enables efficient two-way communication

WebSocket is a two-way communication protocol. Servers and browsers implement protocol stacks to communicate using WebSocket. WebSocket exists because HTTP was not designed to be bidirectional. There are methods to implement two-way connections with HTTP, but they have problems.

WebSocket is a powerful technology, but is not necessary in all cases, as it can significantly complicate application architecture. Client-side WebSocket usage is done with the browser’s WebSocket API.

Comments are closed.