Skip to content
Related Articles

Related Articles

Improve Article

How to Configure Socket.IO with Demo-Chat App in Node.js ?

  • Last Updated : 24 Jun, 2020

For making a chat app, it is required that the server sends data to the client but the client should also respond back to the server. This can be done by making use of the Websockets. A WebSocket is a kind of communication pipe opened in two directions.

Prerequisite:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

  1. Node.js: It is an open source JavaScript back-end technology executed by the server. It has its own package manager npm(Node Package Manager) which allows easy installation of packages.
  2. Expess.js: It is a framework based on Node.js.
  3. Socket.io: It enables real-time bidirectional event-based communication. It works on every platform, browser, or device, focusing equally on reliability and speed. Socket.IO is built on top of the WebSockets API (Client-side) and Node.js. It is one of the most dependent upon the library at npm.

Setting up the Environment: The very first step is to start npm. So, create a new repository and initialize npm using the following commands:

$ mkdir chatApp
$ cd chatApp
$ npm init

Now, the next step is to install npm packages which will be required in building our chat application.



  • express: The web application framework for Node.js.
  • nodemon:(optional) It is used to restart our server. If you don’t want to install it, simply restart server by writing node app.js in the terminal.
  • ejs: A simple templating language that lets you generate HTML markup with plain JavaScript.
  • socket.io: The package that manages Websocket.

Just run the following commands in your terminal to install the above-mentioned packages:

$ npm install --save express
$ npm install --save socket.io
$ npm install --save ejs
$ npm install --save nodemon

Steps to implement code:

Step 1: Create app.js




const express = require('express');
const app = express();
  
app.set("view engine", "ejs");
app.use(express.static("public"));
  
app.get("/", function(req, res) {
    res.send("Welcome to chat app!");
});
  
server = app.listen(3000);

If you run http://localhost:3000 in your browser, you can see the message appearing on your screen as shown below:

Now to configure socket.io, we have to first make an object in app.js file as shown below:




const io = require("socket.io")(server);
  
io.on('connection', (socket) {
     console.log("New user connected");
});

Here, the io object will give us access to the socket.io library. The io object is now listening to each connection to our app. Each time a new user is connecting, it will print the following output:

New user connected

Now for building a window for chat application we will make a html file (actually ejs file) named index.ejs inside views folder. On the other side, public folder will contain css file namely style.css and js file chat.js. It will look like this:



We will now create a route which will render our index.ejs file which opens the window of our chat application.




   
app.get("/", function(req, res) {
    res.render("index.ejs");
});

Now if you will run http://localhost:3000 our chat window will look like this:

Now we will install socket.io on each client which will attempt to connect to our server. To do that, we have to import the socket.io library on the client side:

At the end of your body add these lines:




<script src=
</script>
<script src="chat.js"></script>

Now create a js file named chat.js in the public folder.




$ (function() {
    var socket = io.connect('http://localhost:3000');
});

Step 2: Sending and Receiving Data Now, we will write some code that will enable us to send data as well as receive data from the server.
Changing Username: First of all, we will set a default username as something let’s say “Xyz”. To do so, write down the following code in the app.js and chat.js file.

Filename: app.js




const io = require("socket.io")(server);
io.on('connection', (socket) {
     console.log("New user connected");
     socket.username="xyz";
     socket.on('change_username', (data) {
        socket.username = data.username;
     });
});

Filename: chat.js




$ (function() {
     var socket = io.connect('http://localhost:3000');
     var message = $("#message");
     var username = $("#username");
     var send_message = $("#send_message");
     var send_username = $("#send_username");
     var chatroom = $("#chatroom");
   
     send_username.click(function() {
         console.log(username.val());
         socket.emit('change_username'
           { username : username.val() });
     });
});

socket.emit() allows you to emit custom events on the server and client.

Message: For messages we modify our files as shown below:
Filename: chat.js




$ (function() {
 var socket = io.connect('http://localhost:3000');
 var message = $("#message");
 var username = $("#username");
 var send_message = $("#send_message");
 var send_username = $("#send_username");
 var chatroom = $("#chatroom");
  
 send_message.click(function() {
    socket.emit('new_message', { message : message.val() });
 });
  
 socket.on("new_message", (data) {
   console.log(data);
   chatroom.append("<p class='message'>"
     + data.username+";" + data.message+"</p>")
 });
  
 send_username.click(function() {
   console.log(username.val())
   socket.emit('change_username',
        {username : username.val()})
 });
});

Filename: app.js




const io = require("socket.io")(server);
io.on('connection', (socket) {
 console.log("New user connected");    
   
 socket.username="xyz";
  
 socket.on('change_username', (data) {
   socket.username = data.username;
 });
  
 socket.on('new_message', (data) {
   io.socket.emit('new_message', {
       message : data.message,
       username : socket.username
   });
 });
});

Th final result of our simple chat app will look like this:

A Little Advancement: A little more we can do is add a jQuery event listener on typing and send a socket event named typing.

It will simply display if someone is typing a message. Write the following code in chat.js and app.js as shown below:
Filename: chat.js




message.bind("keypress", () {
    socket.emit('typing');
});
  
socket.on('typing', (data) {
  feedback.html("<p><i>" + data.username 
    + " is typing a message..." + "</i></p>");
});

Filename: app.js




socket.on('typing', (data) {
    socket.broadcast.emit('typing', {username : socket.username});
});



My Personal Notes arrow_drop_up
Recommended Articles
Page :