×

Creating a chat room


In this article, we will focus on creating a private chat room for a community of Engineering.

After user clicks on Computer Engineering Community

index.html


<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Chatter</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
  </head>
  <body>
    <div class="jumbotron jumbotron-fluid" style="background-color:yellow;">
      <div class="container" >
       <center> <h1 class="display-3">Welcome to the community of Engineers</h1>
        <p class="lead">Discuss technology trends with communities of your choice!!!</p></center>
      </div>
    </div>
    <center><div class="container-fluid">
      <div class="row">
       <ul class="list-group col">
          <a href="/computer" class="list-group-item list-group-item-action">Computer Engineering</a>
          <a href="/civil" class="list-group-item">Civil Engineering</a>
          <a href="/mechanical" class="list-group-item">Mechanical Engineering</a>
          <a href="/automobile" class="list-group-item">Automobile Engineering</a>
          <a href="/electrical" class="list-group-item">Electrical Engineering</a>

        </ul>
      
      </div>
    </center>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
  </body>
</html>

index.html is the simple html where users can select the community in which they want to chat.


index.js

We have created public chat application till now. Now in this article, we will apply some constraints like users will only be able to chat in private chat rooms.

Here we route the application depending on users option. In this case, we created five communities Computer Engineering, Civil Engineering, Electrical Engineering, Automobile Engineering, Mechanical Engineering. If the user selects Computer Engineering then app gets routed using the syntax given below,

app.get('/computer', (req, res) => {
    res.sendFile(__dirname + '/public/computer.html');
});

Similarly, you can define links for different communities as you see in this given code .


const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;

server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

app.get('/computer', (req, res) => {
    res.sendFile(__dirname + '/public/computer.html');
});

app.get('/civil', (req, res) => {
    res.sendFile(__dirname + '/public/civil.html');
});

app.get('/electrical', (req, res) => {
    res.sendFile(__dirname + '/public/electrical.html');
});
app.get('/automobile', (req, res) => {
    res.sendFile(__dirname + '/public/automobile.html');
});

app.get('/mechanical', (req, res) => {
    res.sendFile(__dirname + '/public/mechanical.html');
});


If you noticed index.js file previously, sockets were listening directly on io.on But, to create the rooms for the specific community, sockets will listen using community.on.

Similarly, while sending the message you have to use the community namespace to send messages in the specific room. The code is self-explanatory to understand.

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;

// community namespace
const community = io.of('/community');

community.on('connection', (socket) => {
    socket.on('join', (data) => {
        socket.join(data.room);
        community.in(data.room).emit('message', `New connection joined ${data.room} room!`);
    })

    socket.on('message', (data) => {
        console.log(`message: ${data.msg}`);
        community.in(data.room).emit('message', data.msg);
    });

    socket.on('disconnect', () => {
        console.log('user disconnected');

        community.emit('message', 'user disconnected');
    })
})

Final index.js


const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;

server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

app.get('/computer', (req, res) => {
    res.sendFile(__dirname + '/public/computer.html');
});

app.get('/civil', (req, res) => {
    res.sendFile(__dirname + '/public/civil.html');
});

app.get('/electrical', (req, res) => {
    res.sendFile(__dirname + '/public/electrical.html');
});
app.get('/automobile', (req, res) => {
    res.sendFile(__dirname + '/public/automobile.html');
});

app.get('/mechanical', (req, res) => {
    res.sendFile(__dirname + '/public/mechanical.html');
});

// community namespace
const community = io.of('/community');

community.on('connection', (socket) => {
    socket.on('join', (data) => {
        socket.join(data.room);
        community.in(data.room).emit('message', `New connection joined ${data.room} room!`);
    })

    socket.on('message', (data) => {
        console.log(`message: ${data.msg}`);
        community.in(data.room).emit('message', data.msg);
    });

    socket.on('disconnect', () => {
        console.log('user disconnected');

        community.emit('message', 'user disconnected');
    })
})


Create following files

mechanical.html



<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Mechanical Engineering</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <style>
      form { padding: 20px; position: fixed; bottom: 0; width: 50%; padding-right: 50px;}
      #messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee;} 
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <ul id="messagesListen"></ul>
      </div>
      <div class="row">
          <div class="col-lg-6">
            <form action="">
              <div class="input-group">
                  <input id="messageInput" autocomplete="off" type="text" class="form-control" placeholder="Enter a message here..." aria-label="Enter a message here......">
                  <span class="input-group-btn">
                    <button class="btn btn-secondary" type="submit" style="background-color:teal;">Send</button>
                  </span>
                </div>
            </form>
          </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const room = 'mechanical';
      const socket = io('/community');
      $('form').submit(() => {
        let msg = $('#messageInput').val();
        socket.emit('message', { msg, room });
        $('#messageInput').val('');
        return false;
      });

      socket.on('connect', () => {
        // emiting to everybody
        socket.emit('join', { room: room });
      })

      socket.on('message', (msg) => {
        $('#messagesListen').append($('<li>').text(msg));
      })
    </script>
  </body>
</html>

civil.html


<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Civil Engineering</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <style>
      form { padding: 20px; position: fixed; bottom: 0; width: 50%; padding-right: 50px;}
      #messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee;} 
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <ul id="messagesListen"></ul>
      </div>
      <div class="row">
          <div class="col-lg-6">
            <form action="">
              <div class="input-group">
                  <input id="messageInput" autocomplete="off" type="text" class="form-control" placeholder="Enter a message here..." aria-label="Enter a message here......">
                  <span class="input-group-btn">
                    <button class="btn btn-secondary" type="submit" style="background-color:teal;">Send</button>
                  </span>
                </div>
            </form>
          </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const room = 'civil';
      const socket = io('/community');
      $('form').submit(() => {
        let msg = $('#messageInput').val();
        socket.emit('message', { msg, room });
        $('#messageInput').val('');
        return false;
      });

      socket.on('connect', () => {
        // emiting to everybody
        socket.emit('join', { room: room });
      })

      socket.on('message', (msg) => {
        $('#messagesListen').append($('<li>').text(msg));
      })
    </script>
  </body>
</html>

computer.html



<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Computer Engineering</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <style>
      form { padding: 20px; position: fixed; bottom: 0; width: 50%; padding-right: 50px;}
      #messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee;} 
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <ul id="messagesListen"></ul>
      </div>
      <div class="row">
          <div class="col-lg-6">
            <form action="">
              <div class="input-group">
                  <input id="messageInput" autocomplete="off" type="text" class="form-control" placeholder="Enter a message here..." aria-label="Enter a message here......">
                  <span class="input-group-btn">
                    <button class="btn btn-secondary" type="submit" style="background-color:teal;">Send</button>
                  </span>
                </div>
            </form>
          </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const room = 'computer';
      const socket = io('/community');
      $('form').submit(() => {
        let msg = $('#messageInput').val();
        socket.emit('message', { msg, room });
        $('#messageInput').val('');
        return false;
      });

      socket.on('connect', () => {
        // emiting to everybody
        socket.emit('join', { room: room });
      })

      socket.on('message', (msg) => {
        $('#messagesListen').append($('<li>').text(msg));
      })
    </script>
  </body>
</html>

automobile.html


<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Automobile Engineering</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <style>
      form { padding: 20px; position: fixed; bottom: 0; width: 50%; padding-right: 50px;}
      #messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee;} 
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <ul id="messagesListen"></ul>
      </div>
      <div class="row">
          <div class="col-lg-6">
            <form action="">
              <div class="input-group">
                  <input id="messageInput" autocomplete="off" type="text" class="form-control" placeholder="Enter a message here..." aria-label="Enter a message here......">
                  <span class="input-group-btn">
                    <button class="btn btn-secondary" type="submit" style="background-color:teal;">Send</button>
                  </span>
                </div>
            </form>
          </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const room = 'automobile';
      const socket = io('/community');
      $('form').submit(() => {
        let msg = $('#messageInput').val();
        socket.emit('message', { msg, room });
        $('#messageInput').val('');
        return false;
      });

      socket.on('connect', () => {
        // emiting to everybody
        socket.emit('join', { room: room });
      })

      socket.on('message', (msg) => {
        $('#messagesListen').append($('<li>').text(msg));
      })
    </script>
  </body>
</html>

electrical.html


<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Electrical Engineering</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <style>
      form { padding: 20px; position: fixed; bottom: 0; width: 50%; padding-right: 50px;}
      #messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee;} 
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <ul id="messagesListen"></ul>
      </div>
      <div class="row">
          <div class="col-lg-6">
            <form action="">
              <div class="input-group">
                  <input id="messageInput" autocomplete="off" type="text" class="form-control" placeholder="Enter a message here..." aria-label="Enter a message here......">
                  <span class="input-group-btn">
                    <button class="btn btn-secondary" type="submit" style="background-color:teal;">Send</button>
                  </span>
                </div>
            </form>
          </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const room = 'electrical';
      const socket = io('/community');
      $('form').submit(() => {
        let msg = $('#messageInput').val();
        socket.emit('message', { msg, room });
        $('#messageInput').val('');
        return false;
      });

      socket.on('connect', () => {
        // emiting to everybody
        socket.emit('join', { room: room });
      })

      socket.on('message', (msg) => {
        $('#messagesListen').append($('<li>').text(msg));
      })
    </script>
  </body>
</html>


After user clicks on Computer Engineering Community