PHP connection_aborted() 并不总是有效

2022-01-24 00:00:00 connection client php

首先,我在创建这个主题之前阅读了 stackoverflow 中关于 connection_aborted 的许多主题,但我没有找到我想要的解决方案.

First of all i read many of the topics in stackoverflow about connection_aborted before making this topic but i didn't find the solution i wanted.

我希望以下脚本在服务器和客户端之间的连接终止后正确结束.有时有效,有时无效.我不知道为什么.

I want the below script to end properly when the connection has been terminated between the server and the client. Sometime works , sometimes not. I don't know why.

示例代码如下:

<?php

ignore_user_abort( true );
register_shutdown_function( 'shutdown' );


$url = "http://127.0.0.1:8000";
$file_handler = @fopen( $url, "rb" ) or die("Open failed");

foreach ( $http_response_header as $h )
{
    header( $h );
}

$bytes = 0;
while ( ! feof( $file_handler ) and ! connection_aborted() )
{
    $response = stream_get_line( $file_handler, 4096 );
    $bytes += strlen( $response );
    echo $response;
}

fclose( $file_handler );


function shutdown()
{
    global $file_handler;

    if ( ! is_null( $file_handler ) )
    {
        fclose( $file_handler );
        //do some other code
    }

    posix_kill( getmypid(), 9 );
}

?>

我需要做什么才能使其更准确?

What do i need to do to make it more accurate?

谢谢

推荐答案

TCP 要求客户端确认所有发送的数据包,因此服务器至少应该将其检测为发送超时...

TCP requires that ALL sent packets be acknowledged by the client and therefore the server should detect this as a send timeout at the very least...

session_write_close();//to make flush work
while (connection_status() !== 0) {//this will work if the connection is properly shutdown
                                   //or if it is simply disconnected...
  sleep(1);
  echo "whatever";
  ob_flush();
  flush();
}

相关文章