How to avoid my script to freeze
Posted
by
jemz
on Stack Overflow
See other posts from Stack Overflow
or by jemz
Published on 2014-08-20T04:14:53Z
Indexed on
2014/08/20
4:20 UTC
Read the original article
Hit count: 132
I have socket server script that continuously running listening for the GPS device that runs in PHP CLI,my problem is that my socket will freeze if it executes long time,how do I prevent this so that my script will not freeze.I have no idea on this socket.this is the first time that I use socket connection.
I appreciate someone can help my problem.
<?php
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit (0);
$address_server = 'xxx.xxx.xx.xx';
$port_server = xxxx;
$isTrue = true;
socketfunction($address_server,$port_server,$isTrue);
function socketfunction($address,$port,$done){
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sock, $address, $port);
socket_listen($sock);
$clients = array($sock);
while ($done ) {
$file = fopen('txt.log','a');
$read = $clients;
$write = NULL;
$except = NULL;
$tv_sec = 0;
if (socket_select($read, $write , $except, $tv_sec) < 1){
continue;
}
// checking client
if (in_array($sock, $read)) {
$clients[] = $newsock = socket_accept($sock);
$key = array_search($sock, $read);
unset($read[$key]);
}
//handle client for reading
foreach ($read as $read_sock) {
$data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);
if ($data === false) {
$key = array_search($read_sock, $clients);
unset($clients[$key]);
echo "client disconnected.\n";
echo "Remaining ".(count($clients) - 1)."client(s) connected\r\n";
continue;
}
$data = trim($data);
if (!empty($data)) {
echo("Returning stripped input\n");
fwrite($file,$data."\n");
}
} // end of reading foreach
fclose($file);
}//end while
socket_close($sock);
}
?>
Thank you in advance.
© Stack Overflow or respective owner