首页 > 解决方案 > perl6 IO::Socket::Async 服务器因异常而死亡:连接由对等方重置

问题描述

这是回显服务器代码:

#!/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") ;
        }
    }
}

这是客户端代码:

#!/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;

当客户端连接然后没有从服务器检索任何数据,然后关闭连接服务器因以下错误而死:

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

如何优雅地捕获网络错误,使服务器更加健壮?

标签: socketsasynchronousasync-awaitechoraku

解决方案


如果您想在 a Supply(或任何可等待的,如 a Promisewhenever退出时(或当aPromise被破坏时)处理这种情况,您可以在任何时候安装一个QUIT处理程序。它的工作原理很像异常处理程序,因此它希望您以某种方式匹配异常,或者只是default如果您想将所有退出原因视为“正常”。

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

这将输出“哦,不,对等方重置连接”并继续运行。


推荐阅读