Hello fellow PHP-ers,
I hardly encounter unfixable problems when coding in PHP, usually Google helps me out. This time is different, I’ve got a small problem that I wanted to fix for a long time…
So, I have made a class with a couple of functions that help me retreive all ‘Call of Duty 1’ server IP’s and ports from the masterserver. With a function, I can send all these servers a request.
Here’s the code to send and retreive the information from all those servers:
[php] $starttime = microtime(true);
foreach($servers as $key => $server){
$sockets[$key] = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_sendto($sockets[$key], self::PRFX . $datastream, strlen(self::PRFX . $datastream), 0, $server[0], $server[1]);
$time[$key] = microtime(true);
socket_set_option($sockets[$key],SOL_SOCKET,SO_RCVTIMEO,array(“sec”=>0,“usec”=>1));
}
while(microtime(true) - $starttime < .3){
foreach($servers as $key => $server){
$ping = microtime(true);
if(($response = socket_read($sockets[$key],1048)) != “”){
unset($servers[$key]);
echo "Did it - ";
}
echo (microtime(true) - $ping) . “
”;
}
}[/php]
The first foreach loop sends out the same data to all those servers. Next there is a while loop that loops for atleast 300ms. Every loop it tries and read data from sockets, when it read data, the variable will be unlinked so the it won’t try and read from the same socket again. This all works!
I’ll try and explain the problem now. The code above gives me this output:
0.0036249160766602 0.0040791034698486 Did it - 1.4066696166992E-5 Did it - 1.2874603271484E-5 Did it - 1.1920928955078E-5 Did it - 1.0967254638672E-5 Did it - 1.1920928955078E-5 0.0038638114929199 0.0043079853057861 Did it - 1.4066696166992E-5 Did it - 1.1920928955078E-5 Did it - 1.0967254638672E-5 Did it - 1.1920928955078E-5
It echoes 'Did it - ', when it has read data. When it didn’t, it doesn’t echo. The following number is the time in μs it takes to perform the if statement. When there is no data to read, this takes longer than when there is data to read!!
I have around 150 servers to query, and this small delay adds up, so I can’t measure the time a server takes to respond. Any suggestions are welcome, I don’t care if the code is dramatically changed, I just want it to work ;).
If I made any spelling mistakes etc., don’t hestitate to notify me about it.
ThaWalrus