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,
Connection Reset by Peer with a Socket Write ErrorType “ping” along with the server's address. Execute the command. Run “tracert” and the server address to see if the request is successful. Execute “telnet” and enter the server address to see if the local machine ports are open.
Connection Reset by peer means the remote side is terminating the session. This error is generated when the OS receives notification of TCP Reset (RST) from the remote server.
An application gets a connection reset by peer error when it has an established TCP connection with a peer across the network, and that peer unexpectedly closes the connection on the far end.
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
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