rares_dumitrescu
asked on
socket timeout
function connect($ip, $port) {
global $sock;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, "$ip", $port);
switch(socket_select($r = array($sock), $w = array($sock), $f = array($sock), 1))
{
case 1:
echo "Connected\n";
return 1;
break;
case 0:
error("Unable to connect");
return;
break;
case 2:
error("Unable to connect");
return;
break;
}
return;
}
I have this function to connect to a socket, but i want to have a timeout, if it doesen`t connects in 15 seconds to say Timeout
global $sock;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, "$ip", $port);
switch(socket_select($r = array($sock), $w = array($sock), $f = array($sock), 1))
{
case 1:
echo "Connected\n";
return 1;
break;
case 0:
error("Unable to connect");
return;
break;
case 2:
error("Unable to connect");
return;
break;
}
return;
}
I have this function to connect to a socket, but i want to have a timeout, if it doesen`t connects in 15 seconds to say Timeout
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
How about this though?
http://au3.php.net/manual/en/function.stream-set-timeout.php
Example 1. stream_set_timeout() example
<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
echo "Unable to open\n";
} else {
fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
stream_set_timeout($fp, 2);
$res = fread($fp, 2000);
$info = stream_get_meta_data($fp);
fclose($fp);
if ($info['timed_out']) {
echo 'Connection timed out!';
} else {
echo $res;
}
}
?>
http://au3.php.net/manual/en/function.stream-set-timeout.php
Example 1. stream_set_timeout() example
<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
echo "Unable to open\n";
} else {
fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
stream_set_timeout($fp, 2);
$res = fread($fp, 2000);
$info = stream_get_meta_data($fp);
fclose($fp);
if ($info['timed_out']) {
echo 'Connection timed out!';
} else {
echo $res;
}
}
?>
http://en.php.net/manual/en/function.pfsockopen.php
http://en.php.net/manual/en/function.fsockopen.php
You can specify the timeout. Look at the examples on the above links.
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 15);
Hope this helps