Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm working on a webpage which uses PHP to get the state of some servers located in the same machine (exactly 7 servers).

When I was only getting the state of 1 server the page did load fast and everything was ok, but after adding all the servers it takes like 5 seconds to load and sometimes it times out and doesn't load at all.

To get the server status I am using this .php which uses sockets:

PHP
<html>
<?php

class Status {

    public $server;
    public $online, $motd, $online_players, $max_players;
    public $error = "OK";
    function __construct($url, $port = '25565') {
        $this->server = array(
            "url" => $url,
            "port" => $port
        );
        if ( $sock = @stream_socket_client('tcp://'.$url.':'.$port, $errno, $errstr, 1) ) {
            $this->online = true;
            fwrite($sock, "\xfe");
            $h = fread($sock, 2048);
            $h = str_replace("\x00", '', $h);
            $h = substr($h, 2);
            $data = explode("\xa7", $h);
            unset($h);
            fclose($sock);
            if (sizeof($data) == 3) {
                $this->motd = $data[0];
                $this->online_players = (int) $data[1];
                $this->max_players = (int) $data[2];
            }
            else {
                $this->error = "Cannot retrieve server info.";
            }
        }
        else {
            $this->online = false;
            $this->error = "Cannot connect to server.";
        }
    }
}
?>
</html>



And on the page where the state of the servers display the php code is like this:

XML
<?php
    $server = new Status("127.0.0.1", 54122);
    echo "(";
    echo $server->online_players;
    echo "/";
    echo $server->max_players;
    echo ")";
    $var = $server->online;
    if ($var == true) {
        echo "<a href='#' class='online'>ONLINE</a>";
    }
    else {
        echo "<a href='#' class='offline'>OFFLINE</a>";
    }		
?>


The status of the server is retrieved okay and everything works, but what I wanted to know if anyone has any idea to avoid the webpage timing out or improve the load time in any way?

Thanks.
Posted
Updated 10-Aug-15 9:20am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900