Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Simple chat application in node.js

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.60k
    Comment on it

    Today, I am going to show you, how to create a simple chat application in node js using a special model "socket.io". It simply transmits messages from one client to all others.

    For this, I am going to create two files:-

    1: main.js (Server root files)

    2: index.html

     

    For the purpose of simply, I am putting both the files in the same directory.

    In main.js, import http module:-

      var http = require('http');
    

     

    Now, to open index.html file that contains the view, import fs module:-

    Installing fs module:-

      npm install fs

    Importing fs module in the application:-

    var fs = require('fs');

     

    Creating http server:

      var createServerSnippet =  function(req, res) {
        fs.readFile("index.html", function(err, data ) {
            res.end(data);
        }) ;
      }
    
      var app = http.createServer(createServerSnippet).listen(8000);

     

    Since, nodejs is event driven, it required socket.io, it allows you to create a socket connection between the server and clients and send data back and forth.

    To use it, install socket.io as follows:-

      npm install socket.io
    

    Here is the connection code:-

     var io = require('socket.io').listen(app);
      io.sockets.on('connection', function(socket) {
          console.log("socket connected");
    
          socket.on("msgToClient", function(data) {
              io.sockets.emit("msgFromSever", {message: data.msg})
          })
      });

     

    Therefore, main.js will look like this:-

     

     var http = require('http');
      var fs = require('fs');
    
      var createServerSnippet =  function(req, res) {
        fs.readFile("index.html", function(err, data ) {
            res.end(data);
        }) ;
      }
    
      var app = http.createServer(createServerSnippet).listen(8000);
      console.log("listening localhost:8000");
    
      var io = require('socket.io').listen(app);
      io.sockets.on('connection', function(socket) {
          console.log("socket connected");
    
          socket.on("msgToClient", function(data) {
              io.sockets.emit("msgFromSever", {message: data.msg})
          })
      });
    

     

    index.html will look like this:

     

     <script type="text/javascript" src="/socket.io/socket.io.js"></script>
      <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
      <script type="text/javascript">
           var socket = io.connect("localhost:8000");
    
           function sendMessage() {
               var message = $("#msg").val();
               socket.emit("msgToClient",  { msg: message });
           }
    
           socket.on("msgFromSever", function(data) {
             var msgP = "<p> " + data.message + "</p>";
             $(".chats").append(msgP);
           })
      </script>
      <style type="text/css">
           .chats {
           border: 1px solid #ccc;
           height: 180px;
           overflow-y: scroll;
           width: 20%;
           margin-bottom: 30px;
           }
           #msg {  width: 21%;}
      </style>
    
      <h1>Chat</h1>
      <div class="chats"></div>
      <input type="text" id="msg" />
      <button onclick="sendMessage()" >Send</button>

    You can also use socket.io cdn file for client.

    Running the server:

                 node app.js

     

    Open below url in the browser:-

    localhost:8000

     

    Git code:-

    https://github.com/dinesh-rawat/Simple-chat-application-in-node.js

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: