What are WebSockets?

A WebSocket is a persistent connection between a client and server. WebSockets provide a bidirectional, full-duplex communications channel that operates over HTTP through a single TCP/IP socket connection. At its core, the WebSocket protocol facilitates message passing between a client and server.

Chimezie Enyinnaya • Mar 30, 2021

Over the years, the terminology “WebSockets” has been flying over the internet and one must be wondering, what is a WebSocket?

What is a WebSocket?

A WebSocket is a persistent connection between a client and server. WebSockets provide a bidirectional, full-duplex communications channel that operates over HTTP through a single TCP/IP socket connection. At its core, the WebSocket protocol facilitates message passing between a client and server.

To better explain, WebSockets send messages between client in real-time when a connection is created and also interacts with the server to fetch information if required.

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/6063b23a21c3b62712152916_s_AF0368E13AD8E872887AAEB8143D3778043FBD15CB873272067D0AD9643E97DA_1615370512983_FdqeSaZS.png

For a WebSocket to be active, the client has to create a handshake connection with the server to listen for events and get messages across.

Handshake Request

To have access to the WebSocket, a client has to first request for a connection from the server which is a pretty standard HTTP GET request. This process is called a Handshake Request. The client will send the request with a header that looks like this:

Other headers can be added but if the header is not supported or it is misunderstood, the server will respond with a 400 bad request and close the socket.

Use cases of WebSocket

Real-time updates web applications

WebSockets are used in applications that the client side listens to updates that are being sent from the server-side in real-time. WebSockets allows data to be continuously sent from the backend and fetched in the client which in turn makes the application faster and boost performance.

Chat applications

Real-time updates in a requirement in chat applications and so using WebSockets is a necessity. WebSockets enabled a chat application to give its users the benefit of sending, receiving and broadcasting messages.

Multi-player games

WebSockets are crucial in game creation as it relays DOM elements, Canvas and other things faster among players which is important if users are to play and enjoy the game. There are so many other use cases of WebSockets ranging from financial tickers, sport updates and so many other applications that heavily depend on getting real-time data.

WebSocket Vs HTTP

Connection

The HTTP protocol is unidirectional protocol works on the top of TCP protocol which is a connection-oriented transport layer protocol, we can create the connection by using HTTP request methods after getting the response HTTP connection get closed.

WebSocket is a bidirectional communication protocol that can send the data from the client to the server or from the server to the client by reusing the established connection channel. The connection is kept alive until terminated by either the client or the server.

Performance

WebSockets leverage on the use of real-time update to push data from the server to the client to be consumed by the user making it very fast and performant and is used by large applications with huge users base that requires information kept up to date without leaving our the performance of the application. Performance is also certified by WebSockets because when a connection is created it remains that way.

HTTP if properly used, can maximize performance. HTTP requires for connection every time it hits the server and that to a certain extent hinders performance in applications.

High-Frequency Messaging

The WebSocket protocol offers a persistent connection to exchange messages. This means that individual messages don’t incur any additional tax to establish the transport. Taxes such as establishing SSL, content negotiation, and exchange of bulky headers are imposed only once when the connection is established. There is virtually no tax per message.

HTTP may allow multiple requests to reuse a single connection, there will generally be small timeout periods intended to control resource consumption.

Socket.io

Socket.IO is an open-source JavaScript library that allows bi-directional communication between client and server. Bi-directional communications are enabled when a client has Socket.IO in the browser, and a server has also integrated the Socket.IO package. While data can be sent in several formats, JSON is the simplest.

To establish the connection, and to exchange data between client and server, Socket.IO uses Engine.IO. This is a lower-level implementation used under the hood. Engine.IO is used for the server implementation and Engine.IO client is used for the client.

Installation

Before we start the installation of Socket.IO in our local computer, you first need to check if Node and NPM are installed on your computer. You can check them using:

If they are installed, you should get this output:

You can then go ahead and create a new directory to install your Socket.IO and also Express:

After stepping into the directory you can then initialise npm to create a package.json file, then install Socket.IO and Express:

We can set up a development environment using Nodemon. This will start the server and you won’t have to restart it every time. To do that use the code below:

npm i nodemon

Then we install dotenv for our environment variables which will contain the port we will be listening to, in my case 5555. Then install cors to enable CORS on the application when connecting to the WebSocket:

Then we create a .env file in our directory and add our port:

When that is done, we will create an index.js file in the root directory with the following code:

So what is happening in the above code is that, we called on our Socket.IO and created a new connection. Then creates a new listener testSocket that will emit an event containing a message. We have also gone ahead and gotten our port from the .env file to initialize and listen to. So when setting up, we can open a connection to port 5555 and have access to the WebSocket.

Before we wrap up, let’s look at how to connect a client to the Socket.IO server. First, we need to install the Socket.IO client through NPM or use its CDN. We’ll be using NPM:

_npm i use-socket.io-client
_

Now, we can emit and listen to events from and to the WebSocket. The following code should be in a client-side JavaScript file:

Conclusion

Using WebSockets in your applications gives it a performance boost and is a key factor in real-time applications such as chat apps. This tutorial covered what is a WebSocket and how to use it to your advantage in your application and also ran a comparison to know the difference between WebSocket and HTTP. It also covered how to set up socket.IO with express. I hope this introductory article was helpful.

Though in the article we have seen how to set up a WebSockets project in Node.js using Socket.io, WebSockets is language agnostic and hence we could achieve the same thing in our example in other languages.

About the Author

Chimezie Enyinnaya is a software developer and instructor with passion for teaching and sharing his knowledge. You can learn more about him here: https://adonismastery.com and https://twitter.com/ammezie.

Chimezie Enyinnaya

CometChat

Chimezie Enyinnaya is a software developer and instructor with passion for teaching and sharing his knowledge.

Try out CometChat in action

Experience CometChat's messaging with this interactive demo built with CometChat's UI kits and SDKs.