I'm connecting from an android device using java to a server running PHP using DefaultHttpClient.
One test I am doing is to check that the java code gracefully handles itself if the server takes to long in sending data back. If it does take to long it disconnects and retries.
Currently I have setup the connection timeout to 3 seconds by:
HttpConnectionParams.setSoTimeout(httpParameters, 3000);
On the server the PHP script is sleeping for 10 seconds:
sleep(10);
The java code works, if the script takes longer than 3 seconds then it throws a java.net.SocketTimeoutException and then retries again after a small amount of time.
The PHP script continues to run which is not what I want. I've tried testing using connection_aborted straight after the sleep function but it does not catch the client disconnect which has already happened.
ignore_user_abort(true);
sleep(10);
print "black hole";
flush();
if(connection_aborted()!=0){
// You would think this works but it does not.
}
Whats the recommended way to handle this?
I actually wrote an article on this very subject not too long ago, I will give a brief answer here, and assume it's ok to also post a related link?
Essentially, PHP will only figure out that a remote client has disconnected when it tries to use the socket that is connected to that remote socket, until you ask it to do anything with that socket it will assume that everything is fine. Here is the code I use to check for remote disconnections:
public function isAlive(){
$res = @socket_recv($this->sockHandle, $data, 1024, MSG_PEEK);
if($res === 0){
return false;
}else{
return true;
}
}
The important part here is the MSG_PEEK stops any pending messages from being cleared, and the "@" mutes errors if the socket is ok, but no messages are pending.
For the full article, it's available here:
http://www.bracketbrotherhood.com/remote-disconnections-php-non-blocking-server-sockets/programming-and-development/
Regards, Phil,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With