Web-Socket in NodeJS

What is a Web Socket?
Web Socket is a protocol which provides a full duplex(multiway) communication i.e allows communication in both directions simultaneously. It is a modern web technology in which there is a continuous connection between the user’s browser(client) and the server. In this type of communication, between the web server and the web browser, both of them can send messages to each other at any point in time. Traditionally in the web, we had a request/response format where a user sends an HTTP request and server responds to that. This is still applicable in most of the cases, especially those using RESTful API. But a need was felt for the server to also communicate with the client, without getting polled(or requested) by the client. The server in itself should be able to send information to the client or the browser. This is where Web Socket come into the picture.

In order to make use of the Socket in NodeJS, we first need to install a dependency that is socket.io. We can simply install it by running below command in cmd and then add this dependency to your server-side javascript file also install an express module which is basically required for server-side application

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

Note: npm in the above commands stands for node package manager, a place from where we install all the dependencies. –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies.
Create server in your server side javascript file:

filter_none

edit
close

play_arrow

link
brightness_4
code

const express = require('express'); // using express
const socketIO = require('socket.io');
const http = require('http'
const port = process.env.PORT||3000 // setting the port 
let app = express();
let server = http.createServer(app)
let io = socketIO(server)
  
server.listen(port);

chevron_right


Now we need to make a connection from the server side to the client side through which the server will be able to send data to the client.

// make a connection with the user from server side
io.on('connection', (socket)=>{
  console.log('New user connected');
});

Similarly, 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.



filter_none

edit
close

play_arrow

link
brightness_4
code

<script src="/socket.io/socket.io.js"></script>
<script>
var socket=io()
// make connection with server from user side
socket.on('connect', function(){
  console.log('Connected to Server')
  
});
</script>

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// listener when server emit any message
socket.on('createMessage', (newMessage)=>{
    console.log('newMessage', newMessage);
  })

chevron_right


Now either data can be sent from any side so that a connection is generated between server and client. Then if the server emits a message then the client can listen to that message or if the client emits message then the server can listen to that message. So we have to generate socket for both messages emit and message listen on both the server and the client side.

Server-side code Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

const express=require('express');
const socketIO=require('socket.io');
const http=require('http')
const port=process.env.PORT||3000
var app=express();
var io=socketIO(server);
  
// make connection with user from server side
io.on('connection', (socket)=>{
  console.log('New user connected');
   //emit message from server to user
   socket.emit('newMessage', {
     from:'jen@mds',
     text:'hepppp',
     createdAt:123
   });
  
  // listen for message from user
  socket.on('createMessage', (newMessage)=>{
    console.log('newMessage', newMessage);
  });
  
  // when server disconnects from user
  socket.on('disconnect', ()=>{
    console.log('disconnected from user');
  });
});
  
server.listen(port);

chevron_right


Output

New user connected
{
  to:'john@ds',
  text:'what kjkljd'
}

Client side code Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
  
    <title>ChatApp</title>
  </head>
  <body class="chat">
        <form id='message-form'>
          <input name='message' type="text"placeholder="Message"
                  autofocus autocomplete="off"/>
          <button >Send</button>
        </form>
  
<script src="/socket.io/socket.io.js"></script>
<script>
var socket=io()
  
// connection with server
socket.on('connect', function(){
  console.log('Connected to Server')
  
});
  
// message listener from server
socket.on('newMessage', function(message){
 console.log(message);
});
  
// emits message from user side
socket.emit('createMessage', {
  to:'john@ds',
  text:'what kjkljd'
});
  
// when disconnected from server
socket.on('disconnect', function(){
  console.log('Disconnect from server')
});
</script>
  </body>
</html>

chevron_right


Output:

Connected to Server
{
     from:'jen@mds',
     text:'hepppp',
     createdAt:123
}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.