apache - PHP: socket_write hangs when client disconnects while writing -


while i'm receiving data in ios app (some data received, not all) purposely quit app , socket_write hangs on server. here relevant code:

error_log("start write"); $sent = socket_write($client, $string, $length); error_log("end write"); 

i "start write" message in error log, that's it, continues hang until restart php program.

i tried setting timeout, tried upload large file , looks timed out before upload completed. thought timeout period of inactivity, not total time client connected for. anyways appreciated. assumed socket_write return if socket disconnected, either i'm wrong or code is. help.

edit

basically, need know when client has disconnected. looks fwrite, socket_send, , socket_write hang when client disconnects mid-write , blocking mode on. if set blocking mode off, code looks this:

function send_data($client, $string) {     $length = strlen($string);     socket_set_nonblock($client);     while(true)     {         $sent = socket_write($client, $string, $length);         //or - $sent = socket_send($client, $string, $length, 0);          if($sent === false)         {             error_log("false");             return;         }         if($sent < $length)         {                 $string = substr($string, $sent);                 $length -= $sent;         }         else             return;       } } 

the problem that, $sent === false when client disconnects, when temporarily unavailable, proved happen after sending first few bytes, not sending whole string.

you should use socket_select() determine whether socket ready writing; in manner need write when other side ready receive.

you still need check how many bytes transferred , reduce message accordingly.

for example:

function send_data($client, $string) {     socket_set_nonblock($client);      while ($string != '') {         $write = [$client]; $read = $except = null;         // set timeout 1s         $n = socket_select($read, $write, $except, 1);         if ($n === false) {             return;         } elseif ($n > 0) {             $length = strlen($string);             $sent = socket_write($client, $string, $length);             if ($sent === false || $sent == $length) {                 return;             } else /* $sent < $length */ {                 $string = substr($string, $sent);             }         }     } } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -