Reputation: 1365
I'm creating this website which lists minecraft servers. Basically I'm trying to ping all these servers as they are displayed. Solving this problem with php doesn't quite solve it for me, pinging all the servers takes time, and I know javascript can execute multiple "pings" at the same time. How would I do this?
The PHP code I'm using now:
class minecraft_server
{
private $address;
private $port;
public function __construct($address, $port = 25565){
$this->address = $address;
$this->port = $port;
}
public function get_ping_info(&$info){
$starttime = microtime(true);
$socket = @fsockopen($this->address, $this->port, $errno, $errstr, 1.0);
$stoptime = microtime(true);
$ping = round(($stoptime-$starttime)*1000);
if ($socket === false){
return false;
}
fwrite($socket, "\xfe\x01");
$data = fread($socket, 256);
if (substr($data, 0, 1) != "\xff"){
return false;
}
if (substr($data, 3, 5) == "\x00\xa7\x00\x31\x00"){
$data = explode("\x00", mb_convert_encoding(substr($data, 15), 'UTF-8', 'UCS-2'));
}else{
$data = explode('§', mb_convert_encoding(substr($data, 3), 'UTF-8', 'UCS-2'));
}
if (count($data) == 3){
$info = array(
'version' => '1.3.2',
'motd' => $data[0],
'players' => intval($data[1]),
'max_players' => intval($data[2]),
'ping' => $ping
);
}else{
$info = array(
'version' => $data[0],
'motd' => $data[1],
'players' => intval($data[2]),
'max_players' => intval($data[3]),
'ping' => $ping
);
}
return true;
}
}
And you call the function with:
$server = new minecraft_server(IP, PORT);
if (!$server->get_ping_info($info)){
echo "Offline";
}else{
print_r($info);
}
How would I create a similar thing in javascript?
Upvotes: 0
Views: 2940
Reputation: 2635
In your place, I probably would have set up a script that, when called, pings the selected server and prints a parse-able result, then call that script using Ajax whenever a ping needs to be sent.
Upvotes: 1