Web Socket: Gateway for developing real-time Apps

Tausif Khan
6 min readFeb 10, 2020

--

If you are new to Web Socket or if you are wondering what Web Sockets are, stick around, else you can dive right into the Integration of Web Socket with React section.

The history of Web Socket is out of scope for this article, but its definition holds valuable meaning. The web socket technology allows a two-way communication between two computers over a single TCP. Simplistically put, it is a good way of handling transfer of high-scale data between a server and clients connected to it. Now you might wonder, “how is it different than a traditional request to get data from server?”. The beauty of this technology is, the client does not need to send a GET request every-time an event occurs, the server sends the response to its connected clients automatically, thus avoiding long-polling.

image courtesy connectenum.com

Web Socket Setup In Node.js with Express using Socket.IO

Among many web socket libraries out there, the most popular web sockets currently developers love to use are Socket.IO, ws, sockjs and websocket node. For the sake of this article and to keep things simple, I will use Socket.IO package in Node.js

Consisting of a Node.js server and a Javascript client library, socket.io provides reliability for handling proxies and load balancers as well as personal firewall and antivirus software and even supports binary streaming. Used by Microsoft, Zendesk and Trello, it even provides real time analytics and can be used for a wide verity of use cases from simple chats to IOT (internet of things).

The “introduction” to the library could be quite a mouthful, so if you don’t understand some of it, no problem, MOVE ON!

The Setup

The basic setup for any web socket is that they need to be running on both the server side to listen for any connection as well as on the client side to establish a connection with the server. Socket.io client will be used in the front-end and socket.io server will be used in the back-end.

Server Side:

Spin up your server-api and “require” socket.io after you required ‘express’. The order here does not matter, it is there so you can visualize where I am requiring it. Once you have done that, having the server listen for any incoming connection is simply a walk-in-the-park.

At this point, the server is doing nothing except console logging when a client gets connected. But we can have this web socket perform additional tasks on multiple connection.

To understand the basic logic behind handling a simple client connection, let our client (from the client side) emit an event called “chat”. Upon receiving this event from the client, the server would send the data it received to all the clients connected to it.

That was fairly simple, so, let’s do something a little bit different. Let’s assume three clients, namely A, B and C are connected to our chat server. Now we want to show ‘A is typing a message” to B and C but not to A; when client A is typing a message. We can achieve that using the following code.

That’s about it. Our server side socket.io setup is complete. At the end of your setup, the code should look like this:

Client Side:

It is a good reminder that you can use socket.io client with any framework for the front-end, but in our case, we will be using React as our front-end framework.

After creating the react app using npx create-react-app, npm install socket.io-client to get the client side of the library. Once that is done, you need to require it.

On the client side, listening to events are done with socket.on and to turn-off listening, simply use socket.off. It should be noted that this particular code is being written on the Chatroom component. The function registerHandler will be used later to register a onMessageReceived callback to update the component’s state and hence, display a new message when received.

With the socket.emit, we can have any custom event be emitted from the client side that the server listens to. Through the second argument, we can pass the actual data. Also, a request-response type relation can be concocted by passing a callback as the third argument. This callback can be used to listen to any response coming from the server after the client has emitted an event. In the above screenshot, the register function emits the event called ‘register’ with name as the data and the cb as the callback.

Self-Web Socket implementation vs Third Party API

Now that we have our basics of web sockets out of the way, I guess the real question is…Do we implement our own web socket or should we simply integrate the functionality to a third-party API and let them take the hassle? is such a company that would do the heavy lifting for you while you can concentrate on building your app.

Well, it kind of depends. For scenario A, imagine, you are building a chatroom for your clan, the Black Ninja, which by the way has 4 members. The sole purpose of your clan’s app is to have a chatting UI so that each member can be in constant communication with each other and that’s about it.

Now, for scenario B, imagine you are in charge of making a food delivery and pick-up app for a group of restaurants in a specific area, where one of the core functionalities would be to maintain real-time communication with the driver who will be delivering the food from the restaurant to the customer. To make this app faster and efficient, you chose your front-end to be React, which therefore implies that you have do complex state-managements.

Scenario B is obviously more complex than A because it has got more business logic and possibly ginormous amount of code to maintain. Hence, it would be sensible to use a third party API, such as Pusher to do all the heavy liftings of a web socket, leaving you more time to concentrate on other core features of the app.

Conclusion

Web sockets are definitely some cool add-ons for your application but their implementation can become cumbersome when they are required to do more job than handling some simple chat, and hence, in such cases, it is wiser to delegate that part of your app’s feature to some third party API if you are not willing to walk that extra mile.

--

--