【问题标题】:PHP connection_aborted() Does not always worksPHP connection_aborted() 并不总是有效
【发布时间】:2014-06-25 04:46:30
【问题描述】:

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

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

示例代码如下:

<?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 );
}

?>

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

谢谢

【问题讨论】:

    标签: php connection client


    【解决方案1】:

    connection_aborted() 的含义是,服务器知道,与客户端的连接已丢失。碰巧的是,情况往往并非如此:

    • 想象一下客户端拔掉网络电缆,走出 WiFi 覆盖范围,用他的手机开车进入地下停车场:客户端和服务器之间没有任何数据包表明连接已终止。这意味着,只有在发送回复不成功时(可能在脚本结束很久之后),服务器才会了解连接断开的情况。
    • 想想一个繁忙的服务器(网络繁忙):很有可能,只有在您的脚本运行相当长的时间后,网络服务器才会接收和处理 connection.ending 数据包。

    长话短说:这是 TCP 的一个属性,可能无法立即检测到连接丢失。

    【讨论】:

    • 是的,我知道它无法在用户断开连接时准确检测到它,但在我的情况下,当用户成功断开连接时,它永远不会关闭! php脚本PID仍然保持打开状态,关闭它的唯一方法是手动杀死它。我不知道为什么会这样。缓冲区有问题吗?我需要使用冲洗或其他东西吗?我想我试过了,但没有用。
    • 做某事,需要在脚本过早结束时撤消并依赖connection_aborted() 根本无法可靠地工作。没有刷新和其他技巧可以改变 TCP 工作方式的现实。
    【解决方案2】:

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

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 1970-01-01
      • 2023-03-15
      • 2019-01-30
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 2015-06-28
      相关资源
      最近更新 更多