30 April 2020
Socket.io tutorial: Real-time communication in web development
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.
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. 😥
👨💻 Work with software development professionals who build scalable apps for big companies such as eSky, StageClip, or Reservix. Ranked as Poland’s top software house by Clutch.
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
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.
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:
main.js. Optionally, you can add
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
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.
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.
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.
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
And the final effect is presented in the video below. 🙌
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!