PHP connection_aborted() 并不总是有效 [英] PHP connection_aborted() Does not always works

查看:36
本文介绍了PHP connection_aborted() 并不总是有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我在创建这个主题之前阅读了 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();
}

这篇关于PHP connection_aborted() 并不总是有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆