0

前段时间我使用查询来检查我的世界服务器的状态。php,但我对结果并不满意。有时它只用了 10 多秒,甚至没有得到状态,尽管 mc 服务器已启动并且网络服务器在同一数据中心内。

您认为哪种方法最稳定且性能最佳:query、stream_stocket 还是其他方法?

我应该每 30 秒运行一次测试吗?一个 cronjob 或只是将结果缓存 30 秒'?

4

1 回答 1

0

您可以使用此代码创建一个 PHP 文件并定期运行以存储状态。

<?php
/**
 * @author Kristaps Karlsons <kristaps.karlsons@gmail.com>
 * Licensed under MPL 1.1
 */

function mc_status($host,$port='25565') {
    $timeInit = microtime();
    // TODO: implement a way to store data (memcached or MySQL?) - please don't overload target server
    $fp = fsockopen($host,$port,$errno,$errstr,$timeout=10);
    if(!$fp) die($errstr.$errno);
    else {
        fputs($fp, "\xFE"); // xFE - get information about server
        $response = '';

        while(!feof($fp)) $response .= fgets($fp);
        fclose($fp);
        $timeEnd = microtime();

        $response = str_replace("\x00", "", $response); // remove NULL

        //$response = explode("\xFF", $response); // xFF - data start (old version, prior to 1.0?)
        $response = explode("\xFF\x16", $response); // data start

        $response = $response[1]; // chop off all before xFF (could be done with regex actually)

        //echo(dechex(ord($response[0])));
        $response = explode("\xA7", $response); // xA7 - delimiter

        $timeDiff = $timeEnd-$timeInit;
        $response[] = $timeDiff < 0 ? 0 : $timeDiff;
    }
    return $response;
}

$data = mc_status('mc.exs.lv','25592'); // even better - don't use hostname but provide IP instead (DNS lookup is a waste)

print_r($data); // [0] - motd, [1] - online, [2] - slots, [3] - time of request (in microseconds - use this to present latency information)

致谢:skakri ( https://gist.github.com/skakri/2134554 )

于 2014-01-27T19:34:03.140 回答