Making WebSocket with NodeJS and HTML5

In this blog we will try to create websocket with the help of HTML5 and NodeJS.

First something about NodeJS or simply Node:-

    Node provides a purely event-driven, non-blocking infrastructure for building highly concurrent software. It internally uses the Google’s V8 JavaScript engine, an event loop, and a low-level I/O API.

    Now First lets check how we can create a websocket in NodeJS:

    simply by taking a reference to socket which is listening on port 8888.

    var io = require('socket.io').listen(8888);
    io.sockets.on('connection', function(socket){ 
      // put your code
    
    });
    

    Now How we will connect to this socket from html:

    Just by:

    var socket = io.connect('localhost', {port: 8888});
    

    Thats all.

    Our aim is to make below application, in which user make some graphics in his/her browser and it simply get replicated at other user browser.

    Screenshot_websocket

    Below is the server code i.e. NodeJS code:

    // Require HTTP module (to start server) and Socket.IO
    var http = require('http')
    var io = require('socket.io').listen(8888);
    
      
    // Add a connect listener
    io.sockets.on('connection', function(socket){ 
    	
    	socket.on('message',function(msg){ 
    	 	socket.broadcast.emit('message', {n:msg});
    	 });
    
    
    	socket.on('disconnect',function(){
    		console.log('Server has disconnected');
    	});
    
        socket.on('iran', function(data){
    	  console.log("**************" + data.todo + "******************");
    	});
    	
    });
    

    Below is HTML5 code:

    <html>
     <head>
      <script language="JavaScript" src="js/jquery-1.8.3.min.js"></script>
     <head>
     <body>
      <script src="http://localhost:8888/socket.io/socket.io.js" type="text/javascript"></script>
    
      <canvas id="canvas" width="500" height="500"></canvas>
    
      <script>
    
      var canvas = $("#canvas");
    
      if(canvas[0].getContext){
       var ctx = canvas[0].getContext("2d");
      } else {
       alert("canvas problem");
      }
    
    
      $(document).ready(function() {
    
    
      var socket = io.connect('localhost', {port: 8888});
      var down = false;
    
      $("#canvas").mousedown(function(){
         down = true;
    	 ctx.beginPath();
         socket.send("dn");
      });
    
    
      $("#canvas").mouseup(function(){
         down = false;
         socket.send("up");
      });
    
    
      $("#canvas").mousemove(function(e){
         if(down == true){
    	 
    	  ctx.strokeStyle = 'green';
    
    	  ctx.lineWidth = 20;
          ctx.lineJoin = "round";
           ctx.lineTo(e.pageX + 1, e.pageY + 1);
    	   ctx.stroke();
    	  socket.send(e.pageX + ":" + e.pageY);
    	 }
    
     
      });
    
     //====================================================================
    
     alert("hello");
    
     socket.on('message', function(msg){
    
     var mh=msg.n;
    
     if(mh == "dn" || mh == "up"){
      ctx.beginPath();
     } else{
      arr = mh.split(":");
     }
    
      ctx.strokeStyle = 'green';
      ctx.lineWidth = 20;
      ctx.lineJoin = "round";
      ctx.lineTo(arr[0],arr[1]);
      ctx.stroke();
     });
    
    
     socket.on('disconnect', function(){
      alert("disconnect");
     });
     
     });
    
    </script>
    
    <body>
    
    </html>
    

Leave a Reply