AppDividend
Latest Code Tutorials

Node js Socket io Tutorial

1,552

Node js Socket io Tutorial is the topic we will deep dive today. 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. Now, first, we need to create a package.json file to install our required dependencies.

Node js Socket io Tutorial

Install the required dev dependencies for our project.

Step 1: Configure the project.

Hit the following command in your terminal.

npm init

Now, to use ES6 in our project, we need to configure babel in our project. So let us install that and also install nodemon for 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 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

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 Socket.io library.

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

npm install --save socket.io

Now, create a 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');
});

Here, I have created a server variable and pass the express application in it. Then connect the socket.io to the server. So when any client sends any request, then 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 root of the project.

npm start

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

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

Step 4: Create a form to enter the message.

Related Posts
1 of 10

So we need to create chat area for our application.

I have built the 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 of all, we need to make connections array to track the no of connections in our application.

Also, open the connection, so that we can connect our client to the socket. 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, then we can find its length on the server. Now we can emit the messages back and forth, and we can get the messages real time. Now open the browser window of this URL: http://localhost:3000/ You can do it on multiple windows, and you can see in the console that more and more sockets are being connected. When we close the window, we still see the two sockets are being 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. If any of the client disconnect with the socket then now we can 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. Now, we need to create an event and send our chat message in 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 just fire an event called sending a message. The server will listen to that event, and we can 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 socket.on() method to listen to that event and log the message sent from the client. So we have successfully sent the message from 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

Finally, our Node js Socket io Tutorial is over. I have put this code on Github.

Github Repository

 

 

Leave A Reply

Your email address will not be published.