#!/opt/sparc/bin/perl5 -w

use Socket;

&init_connection("ow69", "perl_game");
&talk;
&close_connection;


sub talk {

	print "blu!\n";	
	while (undef($data)) { $data = <MYSOCK>;}
	print $data;
	while (!($data =~ /(\\\\)*\\B/)) {
		while ($data =~ s/\\\\/\\/) { }
		print $data;
		print "enter string to send\n";
		$data = <STDIN>;
		print MYSOCK $data;
		while (undef($data)) { $data = <MYSOCK>; }
	}
}

sub close_connection {
	my($timeout, $last_data);
	$lastdata = "";	
	$timeout = 0;
	print "Trying to disconnect from server...\n";
	send(MYSOCK, "\B", 0);
	while($timeout < 5) {
		print "loop\n";
		recv (MYSOCK, $data, 16, 0);
		$lastdata = $lastdata . $data if (defined($data));	
		$timeout++;
		sleep 1;
		if(($lastdata =~ /(\\\\)*\\X/)) {
			print "Disconnect confirmed by server.\n";
			shutdown (MYSOCK, 2);
			close MYSOCK;
			last;
		} elsif (($lastdata =~ /(\\\\)*\\B/)) {
			print "Disconnect request from server.\n";
		}

	}
}

sub init_connection {
        my($service, $remote,$port, $iaddr, $paddr, $proto);

	print "The parameters are:\n";
	foreach (@_) {
		print "\t$_\n";
	}
	print "Trying to connect to $remote on port $port...\n";

        $remote = shift || die "No parameter \$remote";
	$service = shift || die "No parameter \$service";
        $port = getservbyname($service, 'tcp') || 2345;

        $iaddr = inet_aton($remote) || die "No host: $remote";
        $paddr = sockaddr_in($port, $iaddr);
        $proto = getprotobyname('tcp');

        socket(MYSOCK, AF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
        connect(MYSOCK, $paddr) || die "connect: $!";
	print "Connection established...\n";
}

