Web Sockets

Let's swim into the real time world of web


Web Sockets allow us to set up bi-directional persistent communication channels between two or more machines at a time. In this tutorial, our objective is to demonstrate how we can start using websockets in simple steps



# Install Socket.IO


npm install socket.io

# Write Server Code

Once we've installed the socket.io package, it's the time to write some code. Following is a snippet of code we need to write to use socket.io on the server side. You can copy the following code into a file named server.js

// load the require packages 
 const http = require('http');
 const socketio = require('socket.io');
 const fs = require('fs'); 

// create an app instance the way you do normally in node.js 
const app = http.createServer( ( req , res ) => {
  // serve index.html whenever a request hits the server 
  fs.readFile( 'index.html', (err, contents ) => {
      if ( err ) {
        return res.end( ' Error Loading Page ' );
      return res.end( contents ); 
  } );
} );

// initialize socket.io passing the app instance we created above 
const io = socketio( app );

// handle different socket events 
io.on( 'connection' , ( socket ) => {
    socket.emit( 'greeting' , { "Message" : "You are now connected to Socket Server "}  ); 
    socket.on('a', ( data ) => {
    } );
} );

// listen on a port 
app.listen( 3000 ); 

As we can observe in the code snippet above, Sockets work on the concept of events. So both client and server can emit events and react to events asynchronously. On the other hand we can also define handlers to handle events both on the client and server side. emit method is used to trigger events whereas on method is used to define handlers for events.

# Write Client Side Code

Quite similar to the server side, we can write the code on client where first we need to connect to the socket server and then we can start listening and reacting to events. Note that connection event is thrown as soon as the connection to the server is successful.



Love Code. Live Code.