#!/usr/bin/perl

use IO::Socket;

# usage: $0 <host> <ip>

$ip = shift || "127.0.0.1";
$port = shift || 4242;

$cons = 5; # queue size

print "Started $ip:$port\n\n";

$SIG{'QUIT'} = $SIG{'INT'} = $SIG{'TERM'} = $SIG{'HUP'} 
  = sub { print "bang\n"; close $connection; close $server; exit 1 };

$SIG{'PIPE'} 
  = sub { print "pipe\n"; close $connection; close $server; exit 2 };

$server = new IO::Socket::INET ( LocalAddr => $ip,
				 LocalPort => $port,
				 Proto => 'tcp',
				 Reuse => 1,
				 Listen => $cons );

die "$!" unless $server;

while (($connection,$peer) = $server->accept()) {
    
    ($peerport, $peeraddr) = sockaddr_in($peer);
    $peerhost = join(".",unpack ("C4", $peeraddr));

    print "* Connection from: $peerhost:$peerport\n";

    for $i (1..40000) {
      
      printf $connection "%08d %s\n",$i,('x' x 1024);
      print "$i\n" unless $i % 1000;
    }

    close $connection;

    print "* Connection closed\n\n";

}

close $server;

