note 36223 added to function.socket-connect
| From: | seymour at itsyourdomain dot php dot net | Date: | Wed, 01 Oct 2003 16:43:44 +0000 |
| Subject: | note 36223 added to function.socket-connect | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-57550@lists.php.net to get a copy of this message | ||
here's how you can implement timeouts with the socket functions.
this example works for blocking sockets but will work for both blocking and nonblocking with minor
modifications. first call to connect in nonblocking mode returns 115 EINPROGRESS, additional calls
return 114 EALREADY if the connection has not already failed or succeeded. once the connection
succeeds, the socket resource will be returned.
<?
$host = "127.0.0.1";
$port = "80";
$timeout = 15; //timeout in seconds
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
or die("Unable to create socket\n");
socket_set_nonblock($socket)
or die("Unable to set nonblock on socket\n");
$time = time();
while (!@socket_connect($socket, $host, $port))
{
$err = socket_last_error($socket);
if ($err == 115 || $err == 114)
{
if ((time() - $time) >= $timeout)
{
socket_close($socket);
die("Connection timed out.\n");
}
sleep(1);
continue;
}
die(socket_strerror($err) . "\n");
}
socket_set_block($this->socket)
or die("Unable to set block on socket\n");
?>
----
Manual Page -- http://www.php.net/manual/en/function.socket-connect.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+36223
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+36223&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+36223&report=yes