DEV Community

Cover image for Getting Started with Socket.io:Enhancing Real-Time Communication in Web Applications
Opajobi Oyegoke
Opajobi Oyegoke

Posted on

Getting Started with Socket.io:Enhancing Real-Time Communication in Web Applications

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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')
})
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Running Node

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>
Enter fullscreen mode Exit fullscreen mode

(The above code snippet is from socket.io official documentation)
The HTML client side of a simple chat app is shown as follows:
Client

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'));

});
Enter fullscreen mode Exit fullscreen mode

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')
})
Enter fullscreen mode Exit fullscreen mode

(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(

Top comments (1)

Collapse
 
oyegoke profile image
Opajobi Oyegoke
<script src="/socket.io/socket.io.js"></script>

    <script>

        const socket = io();

    </script>
Enter fullscreen mode Exit fullscreen mode

You can be sure that there has been an established connection between client and server by running the server file using Node.

node index.js
Enter fullscreen mode Exit fullscreen mode

Running the above code will listen for a "connection" event that is triggered when a client connects to the server. When a client connects to the server, the callback function (socket) => { console.log('A user is connected ')} is triggered and as such logs it onto the console as shown below;
Connection event

Emitting and Receiving Events

Socket.io is essential in providing real-time communication as it can send and receive any events you want in real time. Let us consider a simple example that entails the user typing in a message on the client side and emitting it to the server as a custom event, the server then listens for this event. When the server gets the 'chat message' event, it logs the message and broadcasts it to all connected clients, making it a powerful tool for real-time communication in web applications.
Let's edit our HTML such that when a user types in a message, the server gets it as a 'chat message' event. It should look like this:

 <script src="/socket.io/socket.io.js"></script>

    <script>

        const socket = io();
        const form = document.getElementById('form');
        const input = document.getElementById('input');

        form.addEventListener('submit', (e) => {
            e.preventDefault();
            if (input.value){
                socket.emit('chat message', input.value);
                input.value='';
            }
        })
    </script>
Enter fullscreen mode Exit fullscreen mode

To listen for this event in our server, we add this in the index.js:

io.on('connection', (socket)=>{
    socket.on('chat message', (msg)=>{
        console.log('message: ' + msg)
    })
Enter fullscreen mode Exit fullscreen mode

This code listens for the connection event which is triggered when a client connects to the server via Socket.io, the socket callback function executes when a connection is established. The callback function sets a listener that listens for the 'chat message ' event and it receives a 'msg' parameter that contains data sent by the client.

Broadcasting

It is not enough to emit events to the server but the server should also emit these received events to all connected clients. In order to send an event to every client connected over the server, Socket.io employs the io.emit( ) method.
So, in our index.js file, instead of console logging the message, we will emit it to all connected clients.

io.on('connection', (socket)=>{
    socket.on('chat message', (msg)=>{
        io.emit('chat message', msg);
    });
Enter fullscreen mode Exit fullscreen mode

Now, let's design our HTML to include a simple chat message interface;

<script src="/socket.io/socket.io.js"></script>

    <script>

      const socket = io();

      const form = document.getElementById('form');

      const input = document.getElementById('input');

      const messages = document.getElementById('messages');

      form.addEventListener('submit', (e) => { // listens for the submit event in form

        e.preventDefault();

        if (input.value) {

          socket.emit('chat message', input.value); // emits chat-message event to socket.io server

          input.value = '';

        }

      });
// broadcast part
      socket.on('chat message', (msg) => {

        const item = document.createElement('li'); //creates new HTML list item

        item.textContent = msg; //sets text content of list to msg received from server

        messages.appendChild(item);

        window.scrollTo(0, document.body.scrollHeight);

      });

    </script>
Enter fullscreen mode Exit fullscreen mode

(code from socket.io)
The first line of the broadcast part listens for 'chat message' event which is emitted by server, the callback function executes when this event occurs. The callback function accepts a msg parameter that contains chat messages sent by server and ultimately broadcasts to all connected clients as shown below.
Simple Chat interface

Conclusion

As you wrap up this exploration of Socket.io, you've gained a fundamental understanding of how it empowers real-time communication between clients and servers. This knowledge serves as a stepping stone, and I encourage you to apply it creatively in your projects. With Socket.io's potential for dynamic real-time updates, you're well positioned to craft innovative and engaging applications that push the boundaries of real-time interactivity.