Uploading ChatBox message notifications

0

Is there any way to refresh the page without being setTimeout or setInterval directly from PHP? if you have it by JS also serves.

I'm making a system of notifications and chats that need to be second by second to be bringing ChatBox message notifications directly from the server, and setInterval is giving some scolding and headaches.

    
asked by anonymous 09.07.2015 / 16:43

1 answer

2

PHP is back-end, there's no way it can make such a direct interaction with the front end.

You have two options:

Ajax + setTimeout

You do not have to want to use setTimeout (it's your friend), an example of ajax with setTimeout:

html:

<div id="respostas"></div>

Js:

function Notificacoes() {
    var request = new XMLHttpRequest();
    request.open("GET", "test.html", true);//true é "assincrono"

    request.onreadystatechange = function (event) {
        if (request.readyState === 4) {
            var target = document.getElementById("respostas");
            var newItem = document.createElement("div");

            if (request.status === 200) {
                 newItem.innerHTML = request.responseText;
            } else {
                 newItem.innerHTML = "Erro na resposta: " + request.status;
            }

            //Adiciona nova mensagem do chat no corpo
            target.appendChild(newItem);

            setTimeout(Notificacoes, 500);//Espera 500ms pra fazer uma nova requisição
        }
    };
    request.send(null);
}

Notificacoes(); //Inicia o Ajax (recomendo window.onload ou $.ready do jQuery)

Another recommendation I make is to bring json data instead of html, as this will be less server consumption and the response will take less time. So with this json data you use javascript to generate the HTML.

Using websockets

WebScokets are more complicated, however the advantage they exert is that the server sends the response because the connection is constant:

js:

var socket = new WebSocket(host);

socket.onopen = function(msg) 
{ 
    if(this.readyState == 1)
    {
        console.log("conectado"); 
    }
};

//Recebe os dados do socket
socket.onmessage = function(msg) 
{
    var target = document.getElementById("respostas");
    var newItem = document.createElement("div");

    newItem.innerHTML = msg.data;

    //Adiciona nova mensagem do chat no corpo
    target.appendChild(newItem);
};

socket.onclose = function(msg) 
{ 
    console.log("Desconectado " + this.readyState); 
};

socket.onerror = function()
{
    console.log("Erro");
};

php:

#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        $talkback = "PHP: You said '$buf'.\n";
        socket_write($msgsock, $talkback, strlen($talkback));
        echo "$buf\n";
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);

PHP documentation:

Why not setInterval

Unlike setTimeout, setInterval does not wait for the process to finish, so if ajax requests are long you can overload the browser.

    
09.07.2015 / 17:01