Socket.io tutorial: Real-time communication in web development

3 min

read

There are a few ways of building a tool for real-time communication. Two of the most popular approaches presuppose the use of HTTP Long Polling or WebSockets. In the article below, you’ll find a brief comparison of both solutions. I decided to focus on the latter solution a little bit more. That’s why in the article, you’ll find a straightforward Socket.io tutorial for building a real-time chat.

What are WebSockets?

WebSockets API is a technology providing a bidirectional communication channel between a client and a server. That means that the client no longer needs to be an initiator of a transaction while requesting data from the server. 

During the first request to the server, except receiving data, it also establishes a WebSocket connection. This process is known as the WebSocket handshake. 🤝 The Upgrade header is included in the request. That’s how the client informs the server that it needs to create a connection.

See also: A few simple tips on how to create WebSocket API in Node.js

WebSockets vs HTTP

So, does it mean it’s impossible to create a chat application without WebSockets? 😨

Well, there is a technique called HTTP Long Polling. Using this, the client sends a request and the server holds that opened until some new data is available. As soon as data appears and the client receives it, a new request is immediately sent and operation is repeated over and over again. However, a pretty big disadvantage of using HTTP Long Polling is that it consumes a lot of server resources. 😥

Socket.io tutorial – building a chat app 🚀

Below, I’ll present to you a brief Socket.io tutorial on how to create a simple chat application with Vanilla JS frontend part and Node.js server. You need to create a project with the default package.json file.

A screenshot with some code for purposes of Socket.io tutorial

Having this created, you need to set up a server and install all the needed dependencies. In order to do it, you need to create an index.js file and install socket.io and express. You can use the following command: touch index.js && npm install express socket.io && npm install --save-dev nodemon.

In index.js, you need to set up a local server and basic socket connection. 

And basically, that’s all you have to do on the backend side at the moment. Once you make a proper request, the connection should be established. It will be visible through the logged message (as shown below).

Now, you need to prepare the frontend part.

Let’s start by creating the public folder and the following files: index.html, main.js. Optionally, you can add style.css

Below, you can see the index.html scaffold. Basically, all you need are HTML tags you can refer to and some scripts from Socket.io included in the project. That’s how your index.html file should look with the WebSockets scripts included.

Then, you need to set up the connection on the frontend side. The only line of code you need in main.js is const socket = io();.  It’s shown in the video below.

As you can see – once the page is opened and the script is loaded, the connection is established. The next thing you need to do is to handle a new user connection, a new message and, last but not least – a currently typing user.

See also: Strapi: Getting started with the Node.js headless CMS

In socket, there are two ways of emitting events. One way is from the user to everyone (including user) and the other which emits an event to all the other instances. The idea is to display the list of all the active users. So, when a user connects – they need to inform about it and get the list of users who are already active.

When a user connects – they emit the event which includes the information about their username. You should set the property of userId on the socket. It will be needed when the user disconnects. To do that – you need to add a username to the Set of active users and emit an event with a list of all active users.

In the main.js I created two functions and two socket listeners.

Firstly, I created a new user (you can easily extend functionality by adding some prompt with a real user name) and emit an event with that username. Also, I added them to the sidebar with all active users. When a user disconnects on the server side – they are removed from the Set of active users and a disconnection event with their username is emitted. After that – they are removed from the sidebar on the client side (as you can notice on the short video below).

Since we handled the way users can connect and disconnect, now it’s time we handle the new messages.

On the server side – you do nothing more than adding the listener shown below.

On the client side – you need to do a few more things, as per the example below.

The function responsible for displaying new messages is triggered right after receiving information from a socket. The message is pushed to the server in the listener function of the form submit. You just need to check if the client is a message author or not. 

Socket.io tutorial screenshot showing an example of a simple chat app

 

Now, I will show you how to emit the event responsible for informing all other connections except yours. We want to display info that a user is typing something at the moment.

On the server side, you need to add socket.broadcast.emit. Take a look below (it is the final version of the file).

On the client side, you need to take a look at inputField keyup event listener and socket listener on typing. Below, you can see both things and the final version of main.js.

And the final effect is presented in the video below. 🙌

See also: Horizontal scaling with WebSocket – tutorial

Summary

I hope that this brief Socket.io tutorial helped you understand how simple is using this approach. And how many interesting things you can do with JavaScript and basic Node.js knowledge.

There are plenty of app ideas based on WebSockets. You can create: 

  • an app that streams matches of your local sports team. You can stream games in the text version or video if possible (or maybe both? 🤔)
  • multiplayer game for you and your friends 🎮
  • secret chat available only for your group 🙊
  • app based on GPS, maybe a game that uses location? 🌏

Your imagination is the limit!

What do you want to achieve?





You can upload a file (optional)

Upload file

File should be .pdf, .doc, .docx, .rtf, .jpg, .jpeg, .png format, max size 5 MB

Uploaded
0 % of

or contact us directly at [email protected]

This site is protected by reCAPTCHA and the Google
Privacy Policy and Terms of Service apply.

Thanks

Thank you!

Your message has been sent. We’ll get back to you in 24 hours.

Back to page
24h

We’ll get back to you in 24 hours

to get to know each other and address your needs as quick as possible.

Strategy

We'll work together on possible scenarios

for the software development strategy in sync with your goals.

Strategy

We’ll turn the strategy into an actionable plan

and provide you with experienced development teams to execute it.

Our work was featured in:

Tech Crunch
Forbes
Business Insider

Aplikujesz do

The Software House

CopiedTekst skopiowany!

Nie zapomnij dodać klauzuli:

Kopiuj do schowka

Jakie będą kolejne kroki?

Phone

Rozmowa telefoniczna

Krótka rozmowa o twoim doświadczeniu,
umiejętnościach i oczekiwaniach.

Test task

Zadanie testowe

Praktyczne zadanie sprawdzające dokładnie
poziom twoich umiejętności.

Meeting

Spotkanie w biurze

Rozmowa w biurze The Software House,
pozwalająca nam się lepiej poznać.

Response 200

Response 200

Ostateczna odpowiedź i propozycja
finansowa (w ciągu kilku dni od spotkania).

spinner

Webinar for CTOs: How to update your company’s legacy software

Sign up