perl6 IO::Socket::Async server dies with the excep

2019-06-17 10:36发布

问题:

Here is the echo server code:

#!/usr/bin/env perl6
my $port = 3333 ;
say "listen port $port" ;

react {
    my $ids = 0 ;
    whenever IO::Socket::Async.listen('0.0.0.0', $port ) -> $conn {
        my $id = $ids++ ;
        $conn.print( "$id: hello\n") ;
        whenever $conn.Supply.lines -> $line {
            say "$id: $line" ;
            $conn.print( "$id : $line\n") ;
        }
    }
}

here is the client code:

#!/usr/bin/env perl6
my $port = 3333 ;
my $conn = await IO::Socket::Async.connect('localhost', $port );
$conn.print: "{time}\n";

#$conn.Supply.tap(-> $v { print $v });

sleep 1 ;
$conn.close;

When the client connect then does not retrieve any data from the server, then closes the connection the server dies with this error:

listen port 3333
0: 1524671069
An operation first awaited:
  in block <unit> at ./server2.p6 line 5

Died with the exception:
    connection reset by peer
      in block <unit> at ./server2.p6 line 5

X::AdHoc+{X::Await::Died}: connection reset by peer

How do I gracefully catch network errors so the server is more robust?

回答1:

If you want to handle the case when a Supply (or any awaitable, like a Promise) underlying a whenever quits (or when the Promise is broken), you can install a QUIT handler inside the whenever. It works a lot like an exception handler, so it will want you to either match the exception somehow, or just default if you want to treat all quit causes as "fine".

whenever $conn.Supply.lines -> $line {
    say "$id: $line" ;
    $conn.print( "$id : $line\n") ;
    QUIT {
        default {
            say "oh no, $_";
        }
    }
}

This will output "oh no, connection reset by peer" and continue running.