saeid ezzati
saeid ezzati

Reputation: 891

how detect aborted connections in stream sockets - php

Im using this code to recieve data and send back data to peer:

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

but second fwrite gave me this error:

Notice: fwrite(): send of 6 bytes failed with errno=10053 An established connection was aborted by the software in your host machine.

now how can I detect aborted connections before sending data ?

Upvotes: 1

Views: 434

Answers (1)

Nate Hammond
Nate Hammond

Reputation: 56

I had something similar and my solution was to convert the PHP warning to an exception and handle it that way. Specifically:

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

It seems best to restore the error handler, so it doesn't mess up code elsewhere.

Upvotes: 2

Related Questions