Monday, 27 February 2017

Real Time Chat With Node JS

Real Time Chat With Node JS

Create a /config.js file (For configuration like Database connection and port)
module.exports = {    
    'SERVERPORT': '8080',            
    'WEBADDRESS': 'http://localhost/',
    'LOG_LEVEL': 'INFO',
    'LOG_FILE_PATH': 'my_log.txt',
    
    
    // MySQL Information
    'MYSQL_HOST': 'localhost',
    'MYSQL_USER': 'root',
    'MYSQL_PASSWORD': '',
    'MYSQL_DB': 'enterprisedev2'
}


Create a /app.js file(Here all nodejs code for working the chat)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
config = require('./config.js');
var mysql = require("mysql");     
request = require('request'),
 util = require('./util')        

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/chat.html');
});

// Log any uncaught exceptions
process.on('uncaughtException', function (exception) {
        console.log(exception); // to see your exception details in the console
        fs.appendFile(config['LOG_FILE_PATH'], exception, null);
});


/* Make DB Connection */
var con = mysql.createConnection({
        host     : config['MYSQL_HOST'],
        user     : config['MYSQL_USER'],
        password : config['MYSQL_PASSWORD'],
        database : config['MYSQL_DB']
}); 

//Check the DB Connection status
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to Db');
        return;
    }
});

  
 

io.on('connection', function(socket) {    
    socket.on('chat message', function(msg) {        
        /** Insert into database **/        
        request(config['WEBADDRESS'] + "ajax/add-chat-message/user_id/" + socket.uid + "/tour_id/" + socket.vid+"/text/"+msg, function(err, res, body) {          
          
          io.sockets["in"](socket.room).emit('chat message', msg,socket.username,socket.vid );
      });            
         
    }); 

    socket.on('new user', function(message, callback) {
        //console.log('New User -' + message);
    });

    socket.on('disconnect', function(message) {
        console.log('user disconnected');
    });

    var usernames = {};
    socket.on('adduser', function(username,vid,uid) {
        console.log(uid);
        var roomName='room_'+vid;
        // store the username in the socket session for this client
        socket.username = username;
        socket.vid = vid;
        //user id
        socket.uid = uid;
        // store the room name in the socket session for this client
        socket.room = roomName;
        // add the client's username to the global list
        usernames[username] = username;
        
         socket.join(roomName);
         //socket.emit('chat message',' You have connected to room1','ChatBot'); //to same window
         socket.broadcast.to(roomName).emit('chat message', username + ' has connected to this room','ChatBot'); //For other windows OR console.
    });
    
    socket.on('updateDetails',function(data){
        console.log(data);
    });

});


http.listen(config['SERVERPORT'], function() {
    console.log('listening on *:'+config['SERVERPORT']);
});



Create chat.html (Here all HTML code where chat will dispaly)

    <ul id="messages"></ul>
<form action="">
<input autocomplete="off" id="m" /><button>Send</button>
        </form>
<script src="//cdn.socket.io/socket.io-1.2.0.js"></script>        
        <script src="//code.jquery.com/jquery-1.11.1.js"></script>
        [style]
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font: 13px Helvetica, Arial; }
            form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
            form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
            form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
            #messages { list-style-type: none; margin: 0; padding: 0; }
            #messages li { padding: 5px 10px; }
            #messages li:nth-child(odd) { background: #eee; }
        [/style]
        [script]     
        var getUrlParameter = function getUrlParameter(sParam) {
            var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                sURLVariables = sPageURL.split('&amp;'),
                sParameterName,
                i;

            for (i = 0; i &lt; sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');

                if (sParameterName[0] === sParam) {
                    return sParameterName[1] === undefined ? true : sParameterName[1];
                }
            }
        };

            var vid=getUrlParameter('vid');
            var userId=getUrlParameter('uid');
            
            //var socket = io();
            var socket = io.connect('http://localhost:8080'); 
            //socket.emit('adduser', prompt("What's your name?"),vid);
            socket.emit('adduser', 'Username',vid,userId);                        
            //socket.emit('updateDetails', "{name:'arun',address:'Mohali phase 7'}");
            
            $('form').submit(function(req) {
                console.log('posted');
                socket.emit('chat message', $('#m').val());
                $('#m').val('');
                return false;
            });



            socket.on('chat message', function(msg, username) {                    
                $('#messages').append($('
<li>').html('<b>' + username + '</b><i>('+new Date(new Date().getTime()).toLocaleString()+')</i>: ' + msg));

            });
            

            $.get("/ajax/chat?vid="+vid, function(data) {
                    data = JSON.parse(data);
                  //console.log(typeof data);
                $.each(data, function( index, value ) {
                    console.log(value)
                    $('#messages').append($('</li>
<li>').html('<b>' + value.display_name + '</b><i>('+value.dateTime+')</i>: ' + value.text));
                });
                
            });
            /** List default records **/
            </li>

        [/script]



Question: How to RUN?
Open /chat.html in browser



Question: Now install the required module in node.js?
Go to the folder where app.js is exist. Execute following command
npm install express
npm install mysql
npm install log4js
npm install request

Question: Do i need to install socket.io?
Yes, IF not installed please install.

Helpful link to install socket.
http://stackoverflow.com/questions/18990494/how-to-install-node-js-npm-socket-io-and-use-them

Question: How to run node?
node app.js