Build your own Web Socket in Node JS

Build your own Web Socket in Node JS

What is a Web Socket?

Web Socket is a protocol which provides a multi-way communication for example: It allows communication in both directions simultaneously. It is a modern web technology in which there is a continuous connection between the user’s browser and the server.

First install a dependency / package socket.io and express. For that we should run below commands in cmd / terminal.

npm install socket.io --save
npm install express --save

Note: --save flag is no longer needed after Node 5.* version, all the modules that we install will be added to dependencies.

Create server in your server side javascript file:

const express = require('express');
const socketIo = require('socket.io');
const http = require('http') 
const port = process.env.PORT || 3001
let app = express();
let server = http.createServer(app)
let io = socketIo(server)
  
server.listen(port);

Now, make a connection from the server side to the client side through which the server will send data to the client.

io.on('connection', (socket)=>{
  console.log('New user has been connected!');
});

From the client side, we need to add a script file and then make a connection to a server through which user send data to a server.

<script src="/socket/socket.io.js"></script>
<script>
var socket=io() 
socket.on('connect', function(){ 
  console.log('Connected with the server!') 
}); 
</script>

Now, send message or data from a server to the user. We have generated a socket “socket.on()” inside the connection that we made from the server side.

socket.on('createMsg', (newMsg)=>{ 
    console.log('newMsg', newMsg); 
}) 

Here, You can send a data from any side so connection will be generate between server and client.
If the server emits a message then the client can listen that message or if the client emits message then the server can listen that message.
We need to generate socket for both messages emit and message listen on both server and the client.

Server-side code Example:

const express=require('express'); 
const socketIo=require('socket.io'); 
const http=require('http') 
const port=process.env.PORT || 3001 
var app=express(); 
var io=socketIo(server); 

// Make the connection with client from server
io.on('connection', (socket)=>{ 
	console.log('New user has been connected!'); 

	// Emit the message from server to client
	socket.emit('newMsg', { 
		from:'abc@example.com', 
		text:'hello', 
		createdAt:2010/02/07 
	}); 

	// Listen message from user
	socket.on('createMsg', (newMsg)=>{ 
		console.log('newMsg', newMsg); 
	}); 

	// Server disconnect from client
	socket.on('disconnect', ()=>{ 
		console.log('Disconnect from the client'); 
	}); 
}); 
server.listen(port);

Output:

New user has been connected!
{
  to:'pqr@example.com',
  text:'abc def'
}

Client / User side code example:

<!DOCTYPE html>
<html lang="en" dir="ltr"> 
<head>
	<meta charset="utf-8">
	<title>FirstChatApp</title>
</head>
<body class="chat">
	<form id='msg-form'> 
		<input name='msg' type="text" placeholder="Message"/>
		<button>Send Message</button> 
	</form> 

	<script src="/socket/socket.io.js"></script>
	<script> 
	var socket=io(); 

	// Connection with server
	socket.on('connect', function(){ 
		console.log('Connected to the server!') 
	}); 

	// Message listener from server
	socket.on('newMsg', function(message){ 
		console.log(message); 
	}); 

	// Emit message from user side to server
	socket.emit('createMsg', { 
		to:'pqr@example.com', 
		text:'abc def'
	}); 

	// When disconnect from server
	socket.on('disconnect', function(){ 
		console.log('Disconnected from the server') 
	}); 
	</script>
</body>
</html>

Output:

Connected to the server!
{
     from:'abc@example.com', 
     text:'hello', 
     createdAt:2010/02/07 
}

Conclusions

From this example we can easily create the socket connection and make easily message transfer between client and server.