Socket.io Programming With Example In Node.js

Hello everyone. Today I will explain about socket.io in Node JS. Socket.io is used for real time communication between applications. In chat application and some other applications you can use socket.io. Communication between applications using socket.io is very speedy. Socket.io is also used in IOT (Internet of things) for real time object status.

For using the socket.io we have to use ‘socket.io’ module in js file. For understanding we have an example.

First of all you have to install socket.io from npm as shown in the below command.

>> npm install socket.io

Node.js

For using socket programming you have to have knowledge of creating server in node js, events and callback concepts in node js, so if you are new to this, please read the below articles

  1. NodeJS - Getting Started With Some Basic Functions
  2. Callback Concept And Events In Node.js
  3. Creating Server And Host HTML Page Using Node.js

Now we ahave an example for understanding socket.io so we have created one chat window using socket.io in Node.JS.

  1. First we create a simple server and start its listening on 8083 port which we have learned in previous articles.

    NodeSocketExample.js
    1. var http = require('http')  
    2. var url=require('url')  
    3. var fs=require('fs')  
    4.   
    5. var server= http.createServer(function(request,response){  
    6. var path = url.parse(request.url).pathname;  
    7.       
    8.     switch(path) {  
    9.         case '/' :  
    10.             response.writeHead(200,{'Content-Type':'text/html'})  
    11.             response.write('Hello World, Welcome to Socket Programming');  
    12.             response.end();  
    13.             break;  
    14.           
    15.         default :  
    16.             response.writeHead(404);  
    17.             response.write("opps this doesn't exist - 404");  
    18.             response.end();  
    19.             break;  
    20.     }  
    21.       
    22. });  
    23. server.listen(8083);  
  1. Now create one html page which has one textbox for typing a message, one button for sending a message and one list box for displaying a message.

    chatexample.html

    1. <html>  
    2.    <script src="/socket.io/socket.io.js"></script>  
    3.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>  
    4.   <head>  
    5.     <title>Socket.IO chat</title>  
    6.       
    7.   </head>  
    8.   <body>  
    9.     <form action="">  
    10.   <div id="lblMsg"></div>  
    11.  <input id="m" autocomplete="off" /><button>Send</button>  
    12.       <ul id="messages"></ul>  
    13.   </form>  
    14.   </body>  
    15. </html>  
  1. Now we have to add listener to the socket. So create listener which listens to the server. As shown below.
    1. var io=require('socket.io')(http);  
    2. var listener = io.listen(server);  
    3. listener.sockets.on('connection',function(socket){  
    4. )};  
  1. Now when new user is connected for the first time we are sending one welcome message to it so we are emitting one event as shown below.
    1. var io=require('socket.io')(http);  
    2. var listener = io.listen(server);  
    3. listener.sockets.on('connection',function(socket)  
    4. {  
    5.     socket.emit(‘msgWelcome’,{'message':'Hello User wel-come to Chat window !’});  
    6. )};  
  1. Now we have added function to receive this ‘msgWelcome’ event response on html page side.
    1. <script type="text/javascript">  
    2.       
    3.        $(function () {  
    4.         var socket = io();  
    5.           
    6.         socket.on('msgWelcome’',function(data){  
    7.                $('#lblMsg').text(data.message);  
    8.             });  
    9.           
    10.       });     
    11. </script>  
  1. Now we are creating another event for sending messages from one user to other users. On button click we are emitting the ‘socket_Data_1’ event as shown below.
    1. $(function () {  
    2.       var socket = io();  
    3.   
    4.       $('form').submit(function(){  
    5.         socket.emit('socket_Data_1', $('#m').val());  
    6.         $('#m').val('');  
    7.         return false;  
    8.       });  
    9.   
    10.     });   
  1. Now on JS side we are receiving this ‘socket_Data_1' event and call the ‘message_1’ event.
    1. socket.on('socket_Data_1'function(data){  
    2.              io.emit('message_1',data);  
    3.              });  
  1. Then we are receiving this event on html user side and displaying message in list as shown below
    1. $(function () {  
    2.         var socket = io();  
    3.   
    4.         socket.on('message_1'function(msg){  
    5.           $('#messages').append($('<li>').text(msg));  
    6.         });  
    7.       });  

Full code - NodeSocketExample.js

  1. var http = require('http');  
  2. var url=require('url');  
  3. var fs=require('fs');  
  4. var io=require('socket.io')(http);  
  5.   
  6. var server= http.createServer(function(request,response){  
  7. var path = url.parse(request.url).pathname;  
  8.       
  9.     switch(path) {  
  10.         case '/' :  
  11.             response.writeHead(200,{'Content-Type':'text/html'})  
  12.             response.write('Hello World, Welcome to Socket Programming');  
  13.             response.end();  
  14.             break;  
  15.         case '/chatexample.html' :  
  16.             fs.readFile(__dirname + path,function(error,data){  
  17.                 if(error)  
  18.                 {   
  19.                    response.writeHead(404);  
  20.                    response.write(error);  
  21.                    response.end();   
  22.                 } else {  
  23.                     response.writeHead(200,{'Content-Type':'text/html'});  
  24.                     response.write(data);  
  25.                     response.end();  
  26.                 }  
  27.             });  
  28.             break;  
  29.         default :  
  30.             response.writeHead(404);  
  31.             response.write("opps this doesn't exist - 404");  
  32.             response.end();  
  33.             break;  
  34.     }  
  35.       
  36. });  
  37. server.listen(8083);  
  38. var listener = io.listen(server);  
  39. listener.sockets.on('connection',function(socket){  
  40.       
  41.     socket.emit('msgWelcome’',{'message':'Hello User will come to Chat window !'});  
  42.       
  43.     socket.on('socket_Data_1'function(data){  
  44.               
  45.              io.emit('message_1',data);  
  46.              });  
  47.   });  

Full code - chatexample.html

  1. <html>  
  2.     <script src="/socket.io/socket.io.js"></script>  
  3.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>   
  4.     <script type="text/javascript">  
  5.               
  6.       $(function () {  
  7.         var socket = io();  
  8.           socket.on('msgWelcome’',function(data){  
  9.                $('#lblMsg').text(data.message);  
  10.             });  
  11.           
  12.           
  13.         $('form').submit(function(){  
  14.           socket.emit('socket_Data_1', $('#m').val());  
  15.           $('#m').val('');  
  16.           return false;  
  17.         });  
  18.           
  19.         socket.on('message_1'function(msg){  
  20.           $('#messages').append($('<li>').text(msg));  
  21.         });  
  22.       });                     
  23.     </script>  
  24.   <head>  
  25.     <title>Socket.IO chat</title>  
  26.   </head>  
  27.   <body>  
  28.   <form action="">  
  29.       <div id="lblMsg"></div>  
  30.       <input id="m" autocomplete="off" /><button>Send</button>  
  31.       <ul id="messages"></ul>  
  32.   </form>  
  33.   </body>  
  34. </html>  

Now run the Node js file and open the two browser windows and go to http://localhost:8083/chatexample.html  and check the output as shown below.

output

Thanks for reading my article if you have any queries please ask in comment box.

Up Next
    Ebook Download
    View all
    Learn
    View all