#!/usr/bin/perl # Minimal telnet client use strict; use diagnostics; use warnings; use Glib qw(TRUE FALSE); use Gtk2 '-init'; use Net::Telnet; # Which host to connect to? (For convenience, I'm using a popular MUD) my $host = 'bat.org'; my $port = 23; # (The Net::Telnet object we'll create) my $telnetObj; # Open a Gtk2 window, with a Gtk2::TextView to display incoming text, and a Gtk2::Entry for sending # commands my $window = Gtk2::Window->new('toplevel'); $window->set_title('Minimal telnet client'); $window->set_position('center'); $window->set_default_size(600, 400); $window->signal_connect('delete-event' => sub { Gtk2->main_quit(); exit; }); my $vPaned = Gtk2::VPaned->new(); $window->add($vPaned); $vPaned->set_position(350); my $scrollWin = Gtk2::ScrolledWindow->new(undef, undef); $vPaned->add1($scrollWin); $scrollWin->set_policy('automatic', 'automatic'); $scrollWin->set_border_width(0); my $textView = Gtk2::TextView->new; $scrollWin->add_with_viewport($textView); $textView->can_focus(FALSE); $textView->set_wrap_mode('word-char'); $textView->set_justification('left'); my $buffer = $textView->get_buffer(); my $entry = Gtk2::Entry->new(); $vPaned->add2($entry); $entry->signal_connect(activate => sub { # When the user enters a command, empty the entry box and (if the connection is open), send the # command to the host, and display the command in the textview my $cmd = $entry->get_text(); $entry->set_text(''); if ($telnetObj) { $telnetObj->put($cmd); Gtk2->main_iteration() while Gtk2->events_pending(); my $iter = $buffer->get_end_iter(); $textView->get_buffer->insert_with_tags_by_name($iter, $cmd . "\n"); } }); $window->show_all(); # Set up a main loop my $id = Glib::Timeout->add(100, sub{ &mainLoop($telnetObj, $textView, $buffer) }); if (! $id) { exit; } # Open a telnet connection to the host $telnetObj = Net::Telnet->new( Timeout => 15, ); $telnetObj->open( Host => $host, Port => $port, Errmode => sub { &disconnected(); }, ); # Start Gtk2's main loop Gtk2->main(); # ################################################################################################## sub mainLoop { my ($telnetObj, $textView, $buffer) = @_; my $text = $telnetObj->get( Errmode => sub { }, Timeout => 0, ); if ($text) { # We've received some text from the host. Display it in the textview my $iter = $buffer->get_end_iter(); $buffer->insert_with_tags_by_name($iter, $text); } return 1; } sub disconnected { print "Disconnected\.\n"; exit; } sub connectError { print "Connection error\.\n"; exit; }