#!/usr/local/bin/perl -w
use strict;
use IO::Socket;
my ($host, $port, $kidpid, $server, $line);
my $EOL = "\015\012";		# Paranoia

select STDOUT; $| = 1;
my $P = $0; $P =~ s".*/"";
my $V = $ENV{"V_$P"} || 2;		# Verbose level

if (@ARGV <1) {push @ARGV, 'localhost'}	# Default to local server
if (@ARGV <2) {push @ARGV, '4217'}		# Default port for TCPserver.pl
($host, $port) = @ARGV;

# create a tcp connection to the specified host and port
$server = IO::Socket::INET->new(Proto     => "tcp",
								PeerAddr  => $host,
								PeerPort  => $port)
	   or die "can't connect to port $port on $host: $!";

$server->autoflush(1);		# so output gets there right away
#autoflush $server 1;
select $server; $| = 1; select STDOUT;
print "[Connected to $host:$port]$EOL";

# split the program into two processes, identical twins
die "can't fork: $!" unless defined($kidpid = fork());

# the if{} block runs only in the parent process
if ($kidpid) {				# copy the socket to standard output
	print "READ ...$EOL" if $V>1;
	while (defined ($line = <$server>)) {
		print "RCVD \"$line\"$EOL" if $V>1;
		print STDOUT $line;
	}
	kill("TERM", $kidpid);	# send SIGTERM to child
} else {		# the else{} block runs only in the child process
	# copy standard input to the socket
	while (defined ($line = <STDIN>)) {
		print "SEND \"$line\"$EOL" if $V>1;
		print $server $line;
		print "SENT \"$line\"$EOL" if $V>1;
	}
}

