note 47182 added to function.socket-recv
| From: | dgk at tcde dot ru | Date: | Fri, 05 Nov 2004 11:57:32 +0000 |
| Subject: | note 47182 added to function.socket-recv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-80141@lists.php.net to get a copy of this message | ||
I've used socket_select and socket_recv with a while loop and found myself in trouble when
remote side closed connection. The code below produced infinite loop and socket_select returned
immediately (which lead to high cpu time consumption).
<?
socket_set_nonblock($my_socket);
$streams = array($my_socket/*, ... */);
$lastAccess = time();
while (socket_select($streams, $write = NULL, $except = NULL, SLEEP_TIME_SECONDS,
SLEEP_TIME_MILLISECONDS) !== FALSE) {
if (in_array($my_socket, $streams)) {
while (@socket_recv($my_socket, $data, 8192, 0)) {
echo $data;
}
$lastAccess = time();
} else {
if (time()-$lastAccess > LAST_ACCESS_TIMEOUT) {
break;
}
}
// ...
$streams = array($my_socket/*, ... */);
}
?>
The solution was simple, but quite hard to find because socket_recv is not documented. socket_recv
returns FALSE if there is no data and 0 if the socket is widowed (disconnected by remote side). So I
had just to check return value of socket_recv. The problem now sounds stupid, but I've spend
some time to find it out.
I hope this will save some of somebody's hair ;)
----
Manual Page -- http://www.php.net/manual/en/function.socket-recv.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+47182
Delete -- http://master.php.net/manage/user-notes.php?action=delete+47182&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47182&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47182&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47182&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47182&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47182&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+47182&report=yes
Search -- http://master.php.net/manage/user-notes.php