Question

I have this PHP code:

$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

That '60' is a timeout for the connection. Right after that line, I have:

if (!$fp) {...}

Now: will this line wait for that timeout time before executing the code inside braces?

Was it helpful?

Solution

The code inside the braces will be executed after the call to stream_socket_client() returns. It will return in one of three ways:

  • The connection is successful (returns a socket)
  • The connection explicitly fails - I.E. the connection is rejected or reset by server
  • The connection implicitly fails - I.E. it times out

The first two options are likely to happen within a couple of seconds at the most - it can be reasonably assumed that if you haven't established a connection within 10 seconds, it's not going to work properly. With your current code, the third option will not happen for 60 seconds, which means you may end up waiting for 60 seconds before that code is executed.

This is generally true of pretty much every function in PHP - you will have to wait for one function to finish executing before you can execute the next. There are some exceptions to this rule - and many of these exceptions reside in the area of sockets programming, these are called "non-blocking" operations - but you cannot set a socket to be non blocking until it is connected1. This means that your connect call will always "block" until it either connects or fails - the code inside your braces can never be executed until the socket has failed to connect, and this may take up to 60 seconds.

I suggest you lower this timeout - 60 seconds is unnecessarily long.

Edit

1 You can, in fact, perform connect operations in a non-blocking manner, via the STREAM_CLIENT_ASYNC_CONNECT flag for stream_socket_client(). When using this flag one must use stream_select() to determine whether/when the socket is connected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top