Simple Chat app with Expressjs

2 months ago

Today we going to create Chat application. We going to use Expressjs for server.
Make sure you already install nodejs.
We going to use some command line for this, so you can download Git command line  for this tutorial.

OK lets get started.

- Create a folder chat in c:/project
- right click to your project forlder->Git bash here
-Go to command line:
- Install json file

npm init

Then Open package.json
We need to write some stuff there.

{
  "name": "test",
  "version": "1.0.0",
  "description": "Simple chat app",//add the description
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Kinny",//add your name
  "license": "ISC",//original code end here. The dependencies is the code you need to add
   "dependencies":{
      "socket.io":"*",//* mean lastest io
      "express":"*"// express
  }
}

Then install all dependencies

npm install

folder node_modules will auto create in your project

Create 2 file: server.js and index.html in root project

Server.js

var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );

var app = express();
var server = http.createServer( app );

var io = socket.listen( server );
users=[];
connections=[];
server.listen(process.env.PORT|| 3000 );
console.log('server running....');
app.get('/',function(req,res){
    res.sendFile(__dirname+'/index.html');
});
io.sockets.on('connection',function(socket){
    connections.push(socket);
    console.log('connected: %s sockets connected',connections.length)
    //disconnect
    socket.on('disconnect',function(data){
        //if user is discontetn remove username
      
        users.splice(users.indexOf(socket.username),1);
        updateUsernames();//call update username
        connections.splice(connections.indexOf(socket),1);
        console.log('Disconnected: %s sockets connected',connections.length);
    });
    // send message
    socket.on('send message', function(data){
        console.log(data);
        io.sockets.emit('new message',{msg:data,user:socket.username})
    });
    //new user 
     socket.on('new user', function(data,callback){
       callback(true);
       
       socket.username=data;
       users.push(socket.username);
       
       updateUsernames();//call this function
    });
    function updateUsernames()
    {
        io.sockets.emit('get users',users);
    }
    
});


Index.html


<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

        <!-- jQuery library -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

        <!-- Latest compiled JavaScript -->
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <script src="/socket.io/socket.io.js"></script><!--This is not in project itself but it work-->
        <style>
        </style>
    </head>
    <body>

        <div class="container">
            <!-- form login-->
            <div id="userFormArea" class="row">
                <div class="col-md-12">
                    <form id="userForm">
                        <div class="form-group">
                            <br>
                            <input type="text" class="form-control" id="username" placeholder="your name">

                        </div>
                    </form>
                </div>

            </div>



            <!-- end form login-->
            <div id="messageArea" class="row">
                <div class="col-md-4">
                    <div class="well">
                        <h3>User online</h3>
                        <ul class="list-group" id="users"></ul>
                    </div>
                </div>
                <div class="col-md-8">
                    <div class="chat" id="chat"></div>
                    <form id="messageForm">
                        <div class="form-group">
                            <br>
                            <input type="text" class="form-control" id="message" placeholder="your message">

                        </div>
                    </form>
                </div>



            </div>


        </div>

        <script>
            $(function () {
                var socket = io.connect();
                var $messageArea = $('#messageArea');
                var $messageForm = $('#messageForm');
                var $message = $('#message');
                var $chat = $('#chat');
                var $userFormArea = $('#userFormArea');
                var $userForm = $('#userForm');
                var $users = $('#users');
                var $username = $('#username');

                //submit message
                $messageForm.submit(function (e) {
                    e.preventDefault();
                    //console.log('submnit'); test

                    socket.emit('send message', $message.val());
                    $message.val('');
                });
                //get message
                socket.on('new message', function (data) {
                    $chat.append('<strong>' + data.user + ':</strong> ' + data.msg + '</br>');
                });
                //Login
                $userForm.submit(function (e) {
                    e.preventDefault();
                    // console.log('submnit'); //test

                    socket.emit('new user', $username.val(), function (data) {
                        if (data) {
                            $userFormArea.hide();

                        }
                    });
                    $username.val('');
                });
                socket.on('get users', function (data) {
                    var html = '';
                    for (i = 0; i < data.length; i++)
                    {
                        html += '<li class="list-group-item">' + data[i] + '</i>';

                    }
                    $users.html(html);
                });

            });



        </script>

    </body>
</html>

To run project.

node server

Refresh server any time we have change on server.js file.

user ctr+c to disconnect.
User arror up to call previuos command. Hit enter to run