Wednesday, April 12, 2017

how to use php,nodejs, sokets real time chat web app as mobile backend?

I created php,nodejs, real time chat that dependening on sockets have two javascript files and php file first is

server.js

handle all server side operations like:

    socket.on('new message', function(data){
    var sender = socket.username;
    var message = data.message;
    socket.room = data.roomid;
    socket.broadcast.to(socket.room).emit('receive', {name: sender, msg: message});
});

and

process.php

have php functions to insert and select data from database like:

function update($name,$msg){
    $insert = mysql_query("INSERT INTO message(name, message)       
            VALUES('$name','$msg')");
if($insert){
    echo json_encode(['status'=>'success']);
} else{
    echo json_encode(['status'=>'error']);
}

}

and

client.js handle all client side operations like:

$(function(){
var socket = io.connect( 'http://'+window.location.hostname+':8081' );
    socket.on('receive', function(response){
    console.log('receive:'+response.msg);
    $('.messages').append('<li><div class="msg-lhs"><span class="username">'+localStorage.getItem('username')+'</span> : <span class="msg">'+response.msg+'</span></div><span data-livestamp="'+moment().unix()+'" class="msg-rhs"></span></li>');
    $('.messages').animate({scrollTop: $('.messages').prop("scrollHeight")}, 500);
});

$(document).on('keyup','.message-box',function(e){
    var $this = $(this);
    if(e.which === 13){
        var message = $this.val();
        socket.emit('new message', {message : message, roomid : roomid});
        $('.messages').append('<li><div class="msg-lhs"><span class="username">'+localStorage.getItem('username')+'</span> : <span class="msg">'+message+'</span></div><span data-livestamp="'+moment().unix()+'" class="msg-rhs"></span></li>');
        $('.messages').animate({scrollTop: $('.messages').prop("scrollHeight")}, 500);

        $this.val('');
        updateDB(localStorage.getItem('username'),message); //Update message in DB
    }
});

function updateDB(name,msg){
    $.post('process.php',{method:'update',name:name,msg:msg},function(response){
    });
}

but now i wanna use that app as back-end for mobile real time chat app how can i implement this? or how to use my client side functions in client.js with mobile client?



via Mohamed Maree

Advertisement