Perl AnyEvent::Ping代码分析。

坑爹的Coro。。想要用协程比较坑爹,还要自己改写。瞬间就疯了。。

没办法的情况下,研究了下它的模块代码,具体如下:

sub tcp_ping_syn {
    my $host = shift;
    my $port = shift;
    my $timeout = shift || 5;

    if ((++$PingQueue{$host}{$port}{Requests}) > 1) {
        # Ping already underway...
        return;
    }    
    
    my $cv = AnyEvent->condvar;
    my $startTime;
    my $endTime;
    
    $PingQueue{$host}{$port}{CondVar} = $cv;
    
    tcp_connect $host, $port, sub {
         $endTime = time;
        my ($fh) = @_;
         
        $cv->send(( $fh ? (($endTime - $startTime) * 1000) : undef ));
    },
    sub {
        $startTime = time;
        $timeout;
    };
        
    return undef;
}

尼码。压根就没有返回值。。那它在干嘛呢。。。= = # 瞬间惊呆了。。

前面就是尼码的铺垫,对此没辙,还得继续折腾。看了下只有ACK才会有返回值。具体如下:

sub tcp_ping_ack {
    my $host = shift;
    my $port = shift;
            
    if ($PingQueue{$host}{$port}{Requests} < 1) {
        # No outstanding requests...
        return undef;
    }    

    my $latency = $PingQueue{$host}{$port}{CondVar}->recv;
    
    if ((--$PingQueue{$host}{$port}{Requests}) < 1) {
        # Responded to last request.
        $PingQueue{$host}{$port}{CondVar} = undef;    
    }
    
    return $latency;    
}

但是怎么用还没折腾出来。。看PY怎么说。。貌似laputa73说可以自己再写个Coro::Ping...估计得用SOCKET改写一个。。

原文地址:https://www.cnblogs.com/xiaoCon/p/3360580.html