Getting Started with Socket.io:Enhancing Real-Time Communication in Web Applications
Tags: webdev, javascript, beginners, tutorial
Published: 2023-11-06 14:41:10

### INTRODUCTION

Socket.io is an open-source library for real-time, bi-directional (two-way) communication between clients (web browsers ) and servers. Socket.io allows the connection of multiple clients to a single server and facilitates real-time data sharing between those clients and servers. It provides a convenient and efficient way to establish bidirectional communication channels, enabling clients to send and receive data from the server and between clients in a real-time and interactive manner. This makes it a powerful tool for building applications that require live updates, chat, online gaming, collaborative features, and more.
Socket.io is a versatile library that can be used on various platforms, socket.io provides client-side with a JavaScript library meaning it can be used in web applications built with HTML, CSS, and JavaScript.

### Setting up your Development Environment
To use socket.io, you need to have Node.js and npm ( Node Package Manager )installed on your computer. To install Node.js on Windows or macOS, simply download Node.js installer from the official website. After installation, open your terminal or command prompt and run the following commands to verify that Node.js and npm are installed:

```
node -v
npm -v
```
These commands should display the versions of Node.js and npm indicating that installation was successful.
Now, create a new Node.js project by opening the terminal or command prompt and navigating to your project directory, run the following command to initialize a Node.js project.
```
npm init -y
```
This will create a package.json file that manages your project's dependencies and settings. The next step is to install socket.io as a dependency in the project. This is achieved by simply running the following command:
```
npm install socket.io
```
On installation, socket.io should be added to the list of dependencies in the package.json file created earlier. 
Also note that express, a Node.js framework that we are going to be using, is installed. You can add express to project dependencies simply by running the following command:
```
npm install express@4
```

### Server and Client Setup

### Creating a Socket io Server
Creating a socket io server is pivotal to this process because it is over this server that data are emitted and broadcast from and to the client side. To achieve this, create a JS file in your project directory using a code editor. Here is a simple example of a Socket.io server:
```
const express = require('express'); //imports express from express

const { Server } = require('socket.io'); //imports Server class from socket.io
const { createServer } = require('node:http');

const app = express(); //creates an express app
const server = createServer(app); //setup an HTTP server
const io = new Server(server);//Socket.io server created and et on top of HTTP server

server.listen(3000, () => {
   console.log('server running at http://localhost:3000')
})
```
I will cover this code in the next few lines, express is a popular node.js framework and it simplifies the process of building web applications, and as such it is imported and used to create an express application and set up an HTTP server. It is on this HTTP server that the socket.io server is established. The io. on code handles the actual real-time communication, it is an event handler that listens for a 'connection' event. When a client connects to the Socket.io server. the event is triggered and the callback function (socket) =>{...} runs. 
You can test if it is connected to the server by running the command in your terminal:
```
node ('name of server js file')
```

![Running Node](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/smb415hj2kz6u4gujumh.jpg)

### Setting Up a Basic HTML Client
Here, we are simply going to write HTML code for a simple chat app.
```
<!DOCTYPE html>

<html>

  <head>

    <title>Socket.IO chat</title>

    <style>

      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

  

      #form { background:  #b3ffb3; padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }

      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }

      #input:focus { outline: none; }

      #form > button { background: seagreen; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 5px; outline: none; color: #fff; }

  

      #messages { list-style-type: none; margin: 0; padding: 0; }

      #messages > li { padding: 0.5rem 1rem; }

      #messages > li:nth-child(odd) { background: #efefef; }

    </style>

  </head>

  <body>

    <ul id="messages"></ul>

    <form id="form" action="">

      <input id="input" autocomplete="off" /><button>Send</button>

    </form>

  </body>

</html>
```
(The above code snippet is from socket.io official documentation)
The HTML client side of a simple chat app is shown as follows:
![Client](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7menjqy5vfioaptc2lwn.jpg)

### Establishing a connection between Client and Server
To establish a connection between Client and Server, there is a need to understand the two-way relationship between client and server in establishing a connection for real-time applications using socket.io. First, the server is responsible for serving the HTML file to the client and managing WebSocket connections and real-time communication with clients.
```
const { join } = require('node:path'); //imports join from node


app.get('/', (req, res) => {

  res.sendFile(join(__dirname, 'index.html'));

});
```
Your socket.io server js file should look like this:
```
const express = require('express'); //imports express from express

const { Server } = require('socket.io'); //imports Server class from socket.io

const { join } = require('node:path'); //imports join from node

const { createServer } = require('node:http');

  

const app = express(); //creates an express app

const server = createServer(app); //setup an HTTP server

const io = new Server(server);//Socket.io server created and et on top of HTTP server

  

app.get('/', (req, res) => {

    res.sendFile(join(__dirname, 'index.html'));

  });  

io.on('connection', (socket) => {

     console.log('A user Connected');

     socket.on('disconnect', () => {

        console.log('user disconnected');

      });

});  

server.listen(3005, () => {

   console.log('server running at http://localhost:3005')
})
```
(code snippet from socket.io)
The next step is to create the socket. io-client package on the client side to aid its connection to the server using the socket.io client library. To achieve this, simply add the following code to the client-side HTML file, right before the closing body tag( </body> )