如何在流 PHP 中检测中止的连接


how detect aborted connections in stream php

我使用此代码接收数据并将数据发送回对等体:

$sock = stream_socket_server("tcp://127.0.0.1:9000", $errno, $errorMessage);
if (!$sock) {
    echo "error code: $errno 'n error msg: $errorMessage";
}
$read[0] = $sock;
$write = null;
$except = null;
$ready = stream_select($read,$write,$except,10);
if ($ready) {
    $a = @stream_socket_accept($sock);
    $in = '';
    do {
        $temp = fread($a,1024);
        $in .= $temp;
    } while (strlen($temp));
    var_dump($in);
    $out = '....'//some data
    $out2 = '....'//some data
    fwrite($a,$out);
    fwrite($a,$out2);
}       

但是第二次写作给了我这个错误:

注意:fwrite():发送 6 个字节失败,errno=10053 An 已建立的连接被主机中的软件中止 机器。

现在如何在发送数据之前检测中止的连接?

我有类似的东西,我的解决方案是将 PHP 警告转换为异常并以这种方式处理它。具体说来:

set_error_handler("warning_handler", E_WARNING);    
try{
    $res = fwrite($a,$out);
} catch(Exception $e){
    //handle the exception, you can use $e->getCode(), $e->getMessage()
}   
restore_error_handler();    
....
function warning_handler($errno, $errstr) { 
    throw new Exception($errstr, $errno);   
}

似乎最好恢复错误处理程序,这样它就不会在其他地方弄乱代码。