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. 😥

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.

#node #websockets #web-development #developer

How to Build a Real-Time Communication App with Node.js and WebSockets
14.50 GEEK