How to know when reset connection is peer in php?

Recently, I have been working on creating a TCP server using PHP (from the very beginning I know the wrong choice, but this is the standard standard), so I have reached a point where there is a reliable prototype for testing on it, and this showed good results. at startup, I used socket functions to handle the connection for the server, and it worked fine, but one of the main things in the project was to make the channel secure, so I switched to stream_socket.

what I want is the equivalent of socket_last_error in the stream_socket group, so I can know when the connection to the client is closed or not. current situation, all processes will wait for a timer timeout to free even the client is already closed.

I searched the network and I found that there was no way to figure this out via PHP, and I found that some people opened a ticket asking for it by requesting the equivalent socket_last_error for the stream. https://bugs.php.net/bug.php?id=34380

anyway, to know when the FIN_WAIT signal occurs or not?

Thanks,

+8
php timeout tcp
source share
1 answer

I don’t think the stream_socket family is stream_socket , it seems like this is too high a level.

I tried to make a very hacky decision, I do not know if it will work for you, it is not very reliable:

 <?php set_error_handler('my_error_handler'); function my_error_handler($no,$str,$file,$line) { throw new ErrorException($str,$no,0,$file,$line); } $socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr); if (!$socket) { echo "$errstr ($errno)\n"; } else { while ($conn = stream_socket_accept($socket)) { foreach (str_split('The local time is ' . date('n/j/Y g:i a') . "\n") as $char) { echo $char; try { fwrite($conn,$char); } catch (ErrorException $e) { if (preg_match("/^fwrite\(\): send of 1 bytes failed with errno=([0-9]+) ([A-Za-z \/]+)$/",$e->getMessage(), $matches)) { list($errno,$errstr) = array((int) $matches[1], $matches[2]); if ($errno === 32) { echo "\n[ERROR] $errstr"; // Broken pipe } } echo "\n[ERROR] Couldn't write more on $conn"; break; } fflush($conn); } fclose($conn); } fclose($socket); } echo "\n"; ?> 

Launch: php ./server.php

Connect: nc localhost 8000 | head -c1 nc localhost 8000 | head -c1

Server output:

 The loca [ERROR] Broken pipe [ERROR] Couldn't write more on Resource id #6 
+1
source share

All Articles