equinox79
4/6/2013 - 8:46 AM

ちょっとだけ賢くて、諦めないtelnetコマンドを作りたい

ちょっとだけ賢くて、諦めないtelnetコマンドを作りたい

#!/usr/bin/env perl
use strict;
use warnings;
use Term::ReadLine;
use IO::Socket;
use Data::Printer;
use Encode;
use Getopt::Long;
use Try::Tiny;

&main();

sub main {

    try {
        my $term = &init;
        my $sock = &connect($term);
        while ( &readline($term) ) {
            # TODO: 接続が切れてたら再接続
            if ($_) {
                $sock->print($_);
            }
            else {
                $sock->print("\r\n\r\n");
                print $sock->getlines();
                $sock = &connect($term);
            }
        }
    }
    catch {
        warn "error : $_";
    };
}


sub reverse_line {
    print "hoge";
}

sub init {
    my $term = { 'term' => Term::ReadLine->new('nata') };

    GetOptions(
        "host=s"  => \$term->{'host'},
        "port=i"  => \$term->{'port'},
        "verbose" => \$term->{'varbose'},
    );

    return $term;
}

sub connect {
    my ($term) = @_;
    print "# Connecting... " . $term->{'host'} . ':' . $term->{'port'} . "\n";

    my $sock = undef;
    try {
        $sock = IO::Socket::INET->new(
            PeerHost => $term->{host},
            PeerPort => $term->{port},
            Proto    => "tcp",
            Timeout  => 5,
        ) or die $!;
    }
    catch {
        print $@;
    };

    return $sock;
}

sub readline {
    my ($conn) = @_;

    return
      defined( $_ =
          $conn->{term}->readline("[$conn->{host}:$conn->{port}]> ") );
}