The following example demonstrates TCP socket I/O.
This first piece of code is the client using the Net::TCP
module. It sends nloop string to the mirror
and displays the progress after 1000 I/Os.
The time of the whole process can
be measured by
$ time ./tcp_client_loop.pl server_host 7777 10000
.
#!/usr/bin/perl # # Usage: # # # ./tcp_client_loop.pl server_host 7777 1000 # use Net::TCP; my ( $y, $x); my ( $host, $port, $nloop) = @ARGV; print " host $host, port $port, nloop $nloop \n"; if( !$host || !$port || !$nloop) { print " Usage: \$ ./tcp_client_loop.pl server_host 7777 nloop \n"; goto finish; } tie $x, Net::TCP, $host, $port or die "Failed to tie \$x \n"; my $com = "probe\n"; foreach my $i (1 .. $nloop) { $x = $com; # send a string $y = $x; # receive the answer if( !( $i % 1000)) # output after 1000 I/Os to save time { $y =~ s/^\s*(.*?)\s*$/$1/; # remove blank space print " $i, received: $y \n"; } } $x = "bye\n"; finish: untie $x;
Here is the server that mirrors the strings. Is is started on a remote host.
#!/usr/bin/perl -w # # server, mirror, terminates on 'bye' # # usage: # $ ./tcp_server_mirror.pl # my $text = " " x 128; # # main: Server Program # use IO::Socket::INET; my $sock = IO::Socket::INET->new( Listen => 5, LocalPort => 7777, Reuse => 1, Proto => 'tcp'); my $new_sock = $sock->accept(); my $count = 0; while(1) { $count++; $new_sock->recv( $text, 128); $text =~ s/^\s*(.*?)\s*$/$1/; if( $text =~ /bye/i) { $sock->close(); exit 0; } if( !($count % 1000)) { print "$count, sending $text\n"; } $new_sock->send( "--- $text\n"); }