BEGIN {
	$| = 1; print "1..15\n";
}
END {
	print("not ok 1\n") unless $loaded;
}

use Fan::TCP;
$loaded = 1;
print("ok 1\n");

$Fan::TCP::LOG = 6;

ref($srv = Fan::TCP->new())
	or print("not ok 2\n"), exit(1);
print("ok 2\n");

ref($clt = Fan::TCP->new(tcp_host => 'localhost', tcp_timeout => 3))
	or print("not ok 3\n"), exit(1);
print("ok 3\n");

$start = 31111;
$end = $start + 10;
for ($port = $start; $port <= $end; $port++) {
	last if $srv->do_server(
		tcp_bindaddr => '127.0.0.1',
		tcp_bindport => $port);
	warn("port# $port failed, try next\n");
}
$port <= $end
	or print("not ok 4\n"), exit(1);
print("ok 4\n");

$clt->do_client(tcp_port => $port)
	or print("not ok 5\n"), exit(1);
print("ok 5\n");

ref($new = $srv->new_client)
	or print("not ok 6\n"), exit(1);
print("ok 6\n");

!$clt->getln && $clt->error =~ /timed out/
	or print("not ok 7\n"), exit(1);
print("ok 7\n");

# force to clear error.
$clt->clearerror(1);

$clt->putln('ABCDEF')
	or print("not ok 8\n"), exit(1);
print("ok 8\n");

$new->getln eq 'ABCDEF'
	or print("not ok 9\n"), exit(1);
print("ok 9\n");

$new->putln('OPQRSTUVWXYZ')
	or print("not ok 10\n"), exit(1);
print("ok 10\n");

$clt->getln eq 'OPQRSTUVWXYZ'
	or print("not ok 11\n"), exit(1);
print("ok 11\n");

undef $new;
undef $clt;
undef $srv;

# checking timeout routines...
#
ref($srv = Fan::TCP->new())
	or print("not ok 12\n"), exit(1);
print("ok 12\n");

for ($port++; $port <= $end; $port++) {
	last if $srv->do_server(
		tcp_bindaddr => '127.0.0.1',
		tcp_bindport => $port
	);
	warn("port# $port failed, try next\n") if $Fan::TCP::LOG >= 6;
}

ref($clt = Fan::TCP->new(tcp_host => 'localhost'))
	or print("not ok 13\n"), exit(1);
print("ok 13\n");

$clt->do_client(tcp_port => $port)
	or print("not ok 14\n");
print("ok 14\n");

ref($new = $srv->new_client)
	or print("not ok 15\n"), exit(1);
print("ok 15\n");

undef $new;
undef $clt;
undef $srv;

exit;
