简体   繁体   中英

PHP chat client-server comunication

I am making simple php webChat and using MySQL database. MY comunication is based on AJAX requests where, when someone post message, it will be saved.

function sendData(){

var textData = $('#chatText').val();
console.log(textData);
$.ajax({
        type:'POST',
        url:'saveMessage.php',
        data: {
                message:textData
        },
        dataType: 'text',
        success: function(data){
                $('#sendInfo').html(data);
        },
        error: function(/*jqXHR, exception"*/ts){
                $('#sendInfo').html("Error send" + ts.responseText);
        }       
});

} Messages are loaded from database by another request, where there is set a timer which is sending request on server every 1 second.

    $( document ).ready(function(){
    setInterval(check, 1000);


});

function check(){

    $.ajax({
        type:'GET',
        url:'checkMessages.php',
        dataType:'json',
        success: function(result){
            //$("#messageBox").append(result);

            for(var i in result){
                $("#messageBox").append(result[i].email + ": " + result[i].mesgVal + "<br>");
            }
        },
        error: function(/*jqXHR, exception"*/ts){
                $('#sendInfo').html("Error check " + ts.responseText);
            }   
    });
}

This method is bad because of number of reqests from clients to server. I have searched for better solutions and I found webSockets(WS). My problem is that I am using webHosking and I only found LOCAL HOST tutorials. For example this .

So I am asking if there is a way to make It with WS on webHosting or there is better/ simplier way to do this client/ server comunication.

If you need to stick with PHP, then I would advise using long polling . It's a nicer and more effective solution than the current one.

You can find a nice example of long polling in PHP here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM