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

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:

  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

filter_none

edit
close

play_arrow

link
brightness_4
code

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);

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


At the end of your body add these lines:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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;
     });
});

chevron_right


Filename: chat.js

filter_none

edit
close

play_arrow

link
brightness_4
code

$ (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() });
     });
});

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

$ (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()})
 });
});

chevron_right


Filename: app.js

filter_none

edit
close

play_arrow

link
brightness_4
code

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
   });
 });
});

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Filename: app.js

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


full-stack-img




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.