How to know whenever the connection is reset by peer in php?

1.1k Views Asked by At

I have been working lately on building a TCP server using PHP (I know wrong choice to begin with but this is the work standard), so I have reached a point where there is a reliable prototype to do tests on it and it showed good results. at start I used socket functions to handle to connection for server and it was working good but one of the main things on the project is to make the channel secured so I switched to stream_socket.

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

I have searched the net and I found that there is no way to figure it out through PHP and I have found that some people opened issue ticket about it asking for socket_last_error equivalent for stream. https://bugs.php.net/bug.php?id=34380

so is there anyway to know whenever FIN_WAIT signal is raised or not?

Thank you,

1

There are 1 best solutions below

1
On

I don't think it's possible the stream_socket family, it looks like it's too high level.

I tried making a very hackish solution, I don't know if it will work for you, it's 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

Server output:

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