All Ruby on Rails Node JS Android iOS React Native Frontend

Socket.io - easy way to handle WebSockets

The era of static websites has passed. Now users demand dynamic content and application like look and feel. Instead of constantly reloading the page and hitting F5, the page should adjust itself automatically. Many of this can be accomplished with simple asynchronous requests from javascript. But what if you want to update your app only when there is a new data available on the server?

You could send a ton of requests in a loop but that'll use a lot of bandwidth and with more users could potentially DDoS your server or make it very slow. Web technologies are constantly evolving so it's not exceptional that we have a solution for this problem. It's called WebSockets.

 

Websockets allows us to establish a stateful connection between browser and server so we can exchange pieces of information in both directions. It's more efficient than standard request and response cycle from HTTP.

 

Unfortunately, WebSockets are handled differently on different browsers so it's not easy to implement the cross-browser code. And how about older browsers that don't support WebSockets? We need some kind of wrapper that will work on different browsers and fallback to polling techniques on older ones. Socket.io does exactly that and also provides nice API and many additional features like broadcasting.

 

Installation 

Socket.io is split into two components client and server libraries. Both written in javascript. I assume that you have nodejs and npm installed. If not just follow instructions on the internet.

 

Create a directory for server code and run npm init to create package.json file for the project. Next, add the socket.io library to your project by running

npm install --save socket.io

 

We'll also need express library to make things simple. Installation is as simple as typing

npm install --save express

Echo server 

Let's start with something simple.

 

I think echo server should be enough to demonstrate how easy it is to use socket.io, you can easily extend this example to something more complex.

 

Create a file called server.js and paste this code.

On first three lines, we require libraries that we are going to use. Next, we create HTTP server and express application to be able to define routes easily. You can find more about express framework on its website https://expressjs.com/ . Also, we need to create an instantiate socket.io and assign it to the server to allow WebSocket communication.

 

In the next line, we are using express to define root route ('/') to return the content of index.html file. We will store our client code there just to make things really simple. After that, we use previously created io object to listen on connection event. Every time someone connects to the server via socket.io it'll trigger the callback function. Inside connection callback, we have access to a socket that is connected to the client. From here we can emit events or listen to them.

 

Let's listen to echo event and resend the same payload by emitting echo event to the client. Note that the name echo is our custom event's name. We don't need to declare it anywhere so that's convenient. The last line actually starts the server to listen on port 8080.

Client code

Create index.html file in project's root directory and paste the following code.

The first thing you want to do is to include socket.io library. The file will be served from nodejs server so you can access it. We are adding javascript inside HTML just to make this really simple but you shouldn't do that in production code.

 

Inside the code we are creating a connection to the socket.io server by calling io() function. Next, we are emitting echo event with test as a payload. Now just start the server with nodejs server.js and connect to it by accessing 0.0.0.0:8080 from your browser. You should see the this is a message message in the console immediately.

Conclusion

I think that the most important skill for a software developer is to quickly adapt to new technologies and to always pick the right tool for the task.

Socket.io is really nice and simple. It allows us to easily consume WebSockets in any application. It's great to have it in the toolbox.

 

Photo by Andreas Kind on Unsplash

Let's make the world better for everyone - join us
New Call-to-action
READ ALSO FROM Node.js
Read also
Need a successful project?
Estimate project or contact us