DEV Community

Hassan Zahar Rifat
Hassan Zahar Rifat

Posted on

Wanna Create your Own Version of Messenger? - Learn Setting up Socket.io

Pre-requisite: Basic React.js, Basic Express.js, CLI

Hello amazing developers! Feeling bored? How about starting to make something like Messenger, Whatsapp or text version of Zoom? You know something very basic about React, Express and you're good to go.

Today, we'll start learning Socket.io to serve our goal and at the end of this writing, we'll be able to setup Socket.io perfectly.

What is Socket.io?
-> According to the official documentation, Socket.io is a library that enables real-time, bidirectional, event-based communication between browser (client side) and server.

It uses WebSocket connection (computer communications protocol providing full duplex channel over a TCP connection) whenever possible and if not, it takes HTTP long polling technology (Half duplex connection). WebSocket [a whole another chapter] connection is pretty fast as users can spontaneously send and receive data through this connection.

One important note: Socket.io is easier to use and gives more features than that of WebSocket and also it definitely uses WebSocket for data transportation, but it cannot send data from its client side to WebSocket server and vice-versa. Okay, enough of theoretical jargons. Let's make real good stuff now!

Installation: We have to install socket.io, express, cors, nodemon (to run the server continuously) in node server. Also we need to initialize the server to configure the package.json file and create an index.js file in where we will write the code. Then We'll install react and socket.io-client for client side. Finally, we'll run both the server.

Server side: In package.json, inside "scripts": {...}, add

"start": "node index",
"start-dev": "nodemon index"
Enter fullscreen mode Exit fullscreen mode

Then,

npm init -y
echo null > index.js [using CMD]
npm install -g nodemon
npm install socket.io express cors
npm run start-dev
Enter fullscreen mode Exit fullscreen mode

Client side:

npx create-react-app name-of-the-app
cd name-of-the-app
npm install socket.io-client
npm start
Enter fullscreen mode Exit fullscreen mode

Now what? - Now, first set up the server with some complementary works. we'll import express, cors (!important), the socket.io package. built in http node module (this will be used to create an http server). After that, we'll have to specify the port number with proccess.env.PORT || 5000. (proccess.env.PORT will be used after deployment by the hosting sites).

const express = require('express');
const cors = require('cors');
const socketio = require('socket.io');
const http = require('http');
const port = proccess.env.PORT || 5000;
Enter fullscreen mode Exit fullscreen mode

Now, we'll initialize express and use cors (Cross-Origin Rrsource Sharing >> helps to prevent blocking requests due to different origin. For example, request from localhost:3000 to localhost:5000 will be blocked if we don't use cors ).

const app = express();
app.use(cors());
Enter fullscreen mode Exit fullscreen mode

Now, we'll create an http server on top of express and connect it with socket.io.

const server = http.createServer(app);
const io = socketio(server, {options});
// , {options} won't be written for now;
// will be used in future to handle cors policy
Enter fullscreen mode Exit fullscreen mode

Now, inside the io.on() method 'connection' event will be declared with an instant of socket.

io.on('connection', (socket) => {
    // console.log('New connection!');
    // codes...
});
Enter fullscreen mode Exit fullscreen mode

All the codes related to socket.io will written inside this method. Now, moving on to the client side. To set all up, we'll import socket.io-client and pass the endpoint containing server side url inside the useEffect without any dependency so that it remain connected.

import io from 'socket.io-client';
...
...
// Inside Component
let socket;
useEffect(() => {
    socket = io('http://localhost:5000/')
});
Enter fullscreen mode Exit fullscreen mode

So, thus installation, client-server side initialization and basic setup can easily be handled.

If you like this blog, we'll definitely be going deeper towards Socket.io in my upcoming blogs. Happy developing :3

Top comments (0)