【问题标题】:how detect aborted connections in stream sockets - php如何检测流套接字中的中止连接 - php
【发布时间】:2014-12-26 09:54:22
【问题描述】:

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

$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 给了我这个错误:

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

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

【问题讨论】:

    标签: php sockets


    【解决方案1】:

    我有类似的事情,我的解决方案是将 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);   
    }
    

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

    【讨论】:

      猜你喜欢
      • 2012-04-09
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 2011-05-19
      相关资源
      最近更新 更多