1

If I'm reading multiple $_->{thand}->cmd($cmd) commands through same telnet connection, I've got disconnects.

This manifests as multiple calls to ae_connect(). How to properly send and fetch data under 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;
mpapec
  • 50,217
  • 8
  • 67
  • 127

1 Answers1

0

I don't think AnyEvent and Net::Telnet will work together. AnyEvent is event based where you have multiple event sources and will act on new data depending on the event source, while Net::Telnet just has a single file handle and blocks waiting for exactly the data it needs at the moment.

If you need multiple Net::Telnet connections in parallel you need to use multiple processes or multiple threads or you might try to use Coroutines (e.g. Coro module).

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • Example above actually works as expected except when executing multiple commands from same handle. It even works as it is from local network, but over internet it reconnects. I'm assuming that it has to do with latencies and code is not handling that as it should. Btw, you should be able to execute the script as I've tried it before posting. – mpapec Jun 12 '14 at 19:38
  • Is there some cookbook for Coro, as documentation just like for Anyevent is lacking in examples? – mpapec Jun 12 '14 at 19:40
  • @mpapec: both Coro and AnyEvent have lots of examples and documentation. They both have an eg/ directory with examples, lots of test in t/ which can be used as example and there is an explicit introduction (Intro.pod). – Steffen Ullrich Jun 12 '14 at 20:18