【问题标题】:Multiple telnet clients/commands under AnyEventAnyEvent 下的多个 telnet 客户端/命令
【发布时间】:2014-08-02 19:35:42
【问题描述】:

如果我通过同一个 telnet 连接读取多个 $_->{thand}->cmd($cmd) 命令,我就会断开连接。

这表现为多次调用ae_connect()AnyEvent下如何正确收发数据?

use strict;
use warnings;
use Data::Dumper;

use AnyEvent::Socket;
use AnyEvent;
use Net::Telnet;

$| = 1;

my $arr = [
  { username => "user+ct", passwd => "1234", Host => "92.242.254.8", Port => 1094 },
  { username => "user+ct", passwd => "1234", Host => "92.242.254.8", Port => 1095 },
  { username => "user+ct", passwd => "1234", Host => "92.242.254.8", Port => 1096 },
];

sub main_loop {

   my $cmd = "/ip firewall filter export";

   my $i=0;
   for (@$arr) {

     if (!$_->{thand}) {
       ae_connect($_);
       print("skip ", Dumper $_);
       next;
     }

     # print Dumper $_;
     $i++;
     my $s;
     $s = join "", $_->{thand}->cmd($cmd);
#     print "\n==1>$i  \n$s";
     $s = join "", $_->{thand}->cmd($cmd);
     $s = join "", $_->{thand}->cmd($cmd);

   }
   print "\n\n";
   #die @$arr*1 if $i;
}


sub ae_connect {
  my ($tc) = @_;

  print "=========== $tc->{Host} ============\n";
  tcp_connect $tc->{Host}, $tc->{Port} //23, sub {
    my ($fh) = @_ or return; # die "failed: $!";

    #
    my $t = new Net::Telnet->new(Fhopen => $fh) or return;

    eval { $t->login($tc->{username}, $tc->{passwd}) } or return;
    $t->timeout($tc->{Timeout});

    $tc->{thand} = $t;
    # $tc->{fh} = $fh;
  };

}

my $w = AnyEvent->timer(after => 0, interval => 1, cb => \&main_loop);

my $cv = AnyEvent->condvar;
$cv->recv;

【问题讨论】:

    标签: perl telnet anyevent


    【解决方案1】:

    我认为 AnyEvent 和 Net::Telnet 不会一起工作。 AnyEvent 是基于事件的,您有多个事件源,并将根据事件源对新数据采取行动,而 Net::Telnet 只有一个文件句柄,并阻塞等待它目前需要的数据。

    如果您需要多个 Net::Telnet 并行连接,您需要使用多个进程或多个线程,或者您可以尝试使用协程(例如 Coro 模块)。

    【讨论】:

    • 上面的示例实际上按预期工作,除非从同一个句柄执行多个命令。它甚至可以像来自本地网络一样工作,但通过互联网它会重新连接。我假设它与延迟有关,并且代码没有按应有的方式处理它。顺便说一句,您应该能够像我在发布之前尝试过的那样执行脚本。
    • 是否有一些 Coro 的食谱,因为缺少示例的 Anyevent 文档?
    • @mpapec:Coro 和 AnyEvent 都有很多示例和文档。他们都有一个包含示例的 eg/ 目录,t/ 中的大量测试可以用作示例,并且有一个明确的介绍(Intro.pod)。
    猜你喜欢
    • 2010-09-30
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2015-09-15
    • 2014-11-19
    • 1970-01-01
    相关资源
    最近更新 更多