#!/usr/bin/perl -w use IO::Socket; use Net::hostent; # for OO version of gethostbyaddr $PORT = 9000; # pick something not in use $server = IO::Socket::INET->new( Proto => 'tcp', LocalPort => $PORT, Listen => SOMAXCONN, Reuse => 1); die "can't setup server" unless $server; print "[Server $0 accepting clients]\n"; while ($client = $server->accept()) { $client->autoflush(1); print $client "-Welcome to $0; type help for command list.\n"; $hostinfo = gethostbyaddr($client->peeraddr); my $response = $hostinfo ? $hostinfo->name : $client->peerhost; printf "[Connect from %s]\n", $response; print $client "+Command?\n"; while (<$client>) { if (/quit|exit/i) { last; } elsif (/date|time/i) { print $client "-SELECTED: date/time\n"; } elsif (/who/i ) { print $client "-SELECTED: who\n"; } elsif (/cookie/i ) { print $client "-SELECTED: cookie\n"; } elsif (/motd/i ) { print $client "-SELECTED: motd\n"; } else { print $client "-Commands: quit date who cookie motd\n"; } print $client "+Command?\n"; } close $client; } #### #!/usr/bin/perl -w use strict; use IO::Socket; my ($host, $port, $kidpid, $handle, $line); unless (@ARGV == 2) { die "usage: $0 host port" } ($host, $port) = @ARGV; # create a tcp connection to the specified host and port $handle = IO::Socket::INET->new(Proto => "tcp", PeerAddr => $host, PeerPort => $port) or die "can't connect to port $port on $host: $!"; $handle->autoflush(1); # so output gets there right away print STDERR "[Connected to $host:$port]\n"; # Get/display handshake message from server my $phandshake = get_from_server($handle); map { print $_, "\n" } @$phandshake; # Socket loop while (1) { # Get user input and send it to the server $line = ; print $handle $line; # Get and display server response my $plines = get_from_server($handle); map { print "$_\n" } @$plines; } sub get_from_server { my $handle = shift; my @lines; while (1) { my $line = <$handle>; defined($line) or die "Server closed connection\n"; chomp $line; ($line =~ s/^([-+])//) or die "Invalid server response: '$line'\n"; my $char = $1; push @lines, $line; last if ($char eq '+'); } return [ @lines ]; } #### my $plines = get_from_server($handle); map { print "$_\n" } @$plines;