0

Here is a part of my code :

while(true)
{
    $socket_options = array(
        'socket' => array(
            'bindto' => 'X.X.X.X:0'
       )
    );
    $context = stream_context_create($socket_options);
    $fp = stream_socket_client('tcp://mywebsite.com:80', $errno, $errstr, 1, STREAM_CLIENT_CONNECT, $context);
    fclose($fp);
}

It seems that eveything runs fine, except some time or the time for do $fp = stream_socket_client(...) takes about 5 seconds. It usually take about 0.05 seconds.

As you can see, I've added a timeout of 1 second which is ignoring. And after this 5 seconds, everything seems to be running fine.

With tcpdump, I've tried to see what happens : For example at 18:00:00, we run the function $fp = stream_socket_client(...). We got no error neither no trace in tcpdebug. At 18:00:05, this function unfreezes and so we got the first trace in tcpdebug :

18:00:05.383328 IP4 XXX.39881 > YYY: Flags [S], seq 888461900, win 28800, options [mss 1440,sackOK,TS val 132651022 ecr 0,nop,wscale 7], length 0
18:00:05.385622 IP4 YYY > XXX.39881: Flags [S.], seq 2116836106, ack 888461901, win 14280, options [mss 1440,sackOK,TS val 1826003082 ecr 132651022,nop,wscale 7], length 0

This persons seems to encounter the same problem without any solution : PHP stream_socket_client ignoring timeout

Edit

After some tests, the same problems happens with socket_create:

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, 'X.X.X.X');          
socket_connect($sock, 'mywebsite.com', 80);
[...]
socket_close($sock);

Here are some responses times for some IP:

X.X.X.18 : 5.2102129459381
X.X.X.29 : 5.1817638874054
X.X.X.11 : 5.2263398170471
X.X.X.78 : 5.2547619342804
X.X.X.56 : 5.1963429450989
X.X.X.24 : 5.1876528263092
Community
  • 1
  • 1
Kevin
  • 1,000
  • 2
  • 10
  • 31

1 Answers1

1

It is not ignoring your 1 second timeout, that time isn't being spent attempting to connect. The delay you're seeing is from the DNS lookup necessary because you're passing in a hostname rather than an IP address.

This is not a fast activity. You don't want to be doing it. Use the IP address.

user3942918
  • 25,539
  • 11
  • 55
  • 67