Node Socket.io: How to Use Node.js With Socket.io

We will build a simple chat app today. We will use Node.js for the backend platform and Socket.io for real-time two-way communication. First, we need to create a package.json file to install our required dependencies.

Node Socket.io

WebSocket is the internet protocol that allows for full-duplex communication between servers and clients. This protocol goes beyond the typical HTTP request/response paradigm; with WebSockets, the server may send data to a client without initiating a request, thus allowing for some exciting applications.

Most tutorials you’ll find on WebSockets have you build a chat app, and we will do the same here. We’ll be using the popular Socket.IO Node.js server framework to accomplish this.

Install the required dev dependencies for our project.

Step 1: Configure the project.

Hit the following command in your terminal.

npm init

To use ES6 in our project, we need to configure Babel in our project.

So let us install that and install nodemon for the development server that helps us not to restart every time. So put the following object in the package.json file.

"devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "nodemon": "^1.15.0"
},

Now install the dependencies.

npm install

In the project root, make one file called .babelrc.

{
   "presets": [
     "es2015", "stage-0"
   ]
}

Okay, now create one file called server.js inside the project root. Also, add the start script inside the package.json file.

"scripts": {
    "start": "nodemon ./server.js --exec babel-node -e js"
},

Step 2: Install express and start the server.

Install the packages by typing the following command.

npm install express body-parser --save

We’ll be using the Express webserver to serve our static files, and body-parser extract the entire body portion of an incoming request stream and exposes it to an API endpoint. You’ll see how they are used later in this tutorial.

We added the –save flag as a dependency in our package.json file.

Write the following code into the server.js file.

// server.js

import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';

const app = express();

Step 3: Install the Socket.io library.

Type the following command to install a socket.io library.

npm install --save socket.io

Now, create a node server.

// server.js

import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';

const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
const PORT = 3000;
server.listen(PORT);
console.log('Server is running');

app.get('/', (req, res) => {
   res.sendFile(__dirname + '/index.html');
});

As you can tell, we’re using Express and Socket.IO to set up our server. This is because Socket.IO provides a layer of abstraction over native WebSockets.

It comes with some excellent features, such as a fallback mechanism for older browsers that do not support WebSockets and the ability to create “rooms”.

Here, I have created a server variable and passed the express application. Then connect the socket.io to the server.

So when any client sends any request, it directly listens to that event. Also, create a file called index.html inside the root folder.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Node.js Socket.io Chat Application</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
   WE have configured successfully
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js" type="text/js"></script>
</body>
</html>

To start our server, hit the following command at the project’s root.

npm start

You can see http://localhost:3000. Our server is running correctly.

Also, we have included the jQuery and Socket.io client versions inside the index.html file. We are using CDN here for the demo.

Step 4: Create a form to enter the message.

So we need to create a chat area for our application.

I have built a simple bootstrap layout.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Node.js Socket.io Chat Application</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
   <div class="container">
      <h1 class="jumbotron">
         Node js Socket io Chat Application
      </h1>
      <div class="row" style="margin-top: 70px;">
         <div class="col-md-4"></div>
         <div class="col-md-6">
            <div id="chatArea">
            </div>
            <form id="myForm">
               <div class="form-group">
                  <textarea rows="5" id="txt" cols="5" class="form-control"></textarea>
               </div>
               <div class="form-group">
                  <button type="submit" class="btn btn-success">Send</button>
               </div>
            </form>
         </div>
      </div>
   </div>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
</body>
</html>

Node.js Socket.io Tutorial With Example From Scratch

Step 5: Make a socket connection.

First, we need to make a connections array to track the number of connections in our application.

Also, open the connection so that we can connect with our client. Finally, type the socket. Then, type the following code to ready the socket to listen for the connection.

// server.js

const connections = [];

io.sockets.on('connection',(socket) => {
   connections.push(socket);
   console.log(' %s sockets is connected', connections.length);
});

Now, only one thing is remaining, and that is to connect the socket to the client. So in an index.html page, write the following code.

<script>
   jQuery(document).ready(function() {
         var socket = io.connect();
   });
</script>

So here, we are trying the connect with the socket. If the socket is connected, we can find its length on the server.

Now we can emit the messages back and forth, and we can get the messages in real-time. Now open the browser window of this URL: http://localhost:3000/ 

You can do it on multiple windows, and you can see that more and more sockets are being connected to the console. However, when we close the window, we still see the two sockets connected. So let us fix that.

// server.js

io.sockets.on('connection',(socket) => {
   connections.push(socket);
   console.log(' %s sockets is connected', connections.length);

   socket.on('disconnect', () => {
      connections.splice(connections.indexOf(socket), 1);
   });
});

Now, we are also listening to the disconnect event. So if any clients disconnect with the socket, we can now see it on the console.

Step 6: Listen to the send message event.

Okay, so from the client-side, we have connected to the socket.

We need to create an event and send our chat message to that event. So let us emit an event with our chatbox message.

<script>
      jQuery(document).ready(function() {
         var socket = io.connect();
         var form = jQuery('#myForm');
         var txt = jQuery('#txt');
         var chatArea = jQuery('#chatArea');

         form.submit(function(e) {
            e.preventDefault();
            socket.emit('sending message', txt.val());
            txt.val('');
         })
      });
   </script>

So it is just a basic jquery. We have connected to the socket, so fire an event called sending a message. The server will listen to that event and broadcast it to other clients.

// server.js

io.sockets.on('connection',(socket) => {
   connections.push(socket);
   console.log(' %s sockets is connected', connections.length);

   socket.on('disconnect', () => {
      connections.splice(connections.indexOf(socket), 1);
   });

   socket.on('sending message', (message) => {
      console.log('Message is received :', message);
   });
});

Here, I have used a socket.on() method to listen to that event and log the message sent from the client.

So we have successfully sent the message from the client to the server. Now, the server needs to emit this message to other clients. So let us do that.

// server.js

io.sockets.on('connection',(socket) => {
   connections.push(socket);
   console.log(' %s sockets is connected', connections.length);

   socket.on('disconnect', () => {
      connections.splice(connections.indexOf(socket), 1);
   });

   socket.on('sending message', (message) => {
      console.log('Message is received :', message);

      io.sockets.emit('new message', {message: message});
   });
});

So we are emitting that new message to every client. Now, we need to listen to this event on the client-side also. So let us do that.

<script>
      jQuery(document).ready(function() {
         var socket = io.connect();
         var form = jQuery('#myForm');
         var txt = jQuery('#txt');
         var chatArea = jQuery('#chatArea');

         form.submit(function(e) {
            e.preventDefault();
            socket.emit('sending message', txt.val());
            txt.val('');
         });

         socket.on('new message', function(data){
            chatArea.append('<div class="well">'+data.message+'</div>');
         });
      });
   </script>

So when the new message event is fired, we can listen to that event and update the dom according to it.

Realtime Chat Application using Node.js and Socket.io

That’s it for this tutorial. I have put this code on Github.

Github Repository

See Also

ES6 Modules in Node.js

Node Image Upload

Node Streams

Node File System

Node Async Await

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.