######################################################################### ## ## myClient.pl by Jake Roberts. ## ## A newbies attempt at TCP socket networking and Perl ## ## This client plays ping pong with the server. Its rather simple. ## ## It does demonstrate the importance of defining a protocol for speaking ## to the server. The client must wait his turn to print to the $socket or ## you can get locked up. ## ## That idea was a real trip up for me as a newbie. ## ## Most of the network/socket stuff was taken from examples from ## www.perlmonks.org an excellent web site ## ## ######################################################################### #!/perl/bin/perl -w use strict; use warnings; use IO::Socket::INET; ## Open a connection to the server my $socket = IO::Socket::INET->new( PeerAddr => 'localhost', PeerPort => '1776', Proto => "tcp", Type => SOCK_STREAM) or die "Socket::INET->new: $!\n\n"; ## Modes # 1 = Waiting for server connection # 2 = Wait for Pong then Send Ping ## Play Ping ping with the server my $mode = 1; while (1) { my $response = <$socket>; ## Read data from Server ## It will wait here until it recieves a \n from the server ## Reading data from the server this way kind of sucks because you don't have any type of timeout if ($response) { ## Important to check because if the connection is closed then $response will be undef chomp $response; ## Remove the \n ############ ## This is my ping Protocal. ## The client and server MUST take turns talking or they will get stuck ## So...first the client waits for a Connection Established signal.... ## then the client sends a ping to the server and waits his turn and listens ## for a pong. When a pong is recieved a ping is sent again...and so on. ## They must play like good children and take turns talking and listening ############ ## Mode 1 -- Waiting for connection signal if ($mode == 1) { if ($response eq "Connection Established") { print $response,"\n"; print $socket "ping\n"; ## The server send a Connect so now its our turn to say ping print "ping..."; $mode = 2; } } elsif ($mode == 2) { ## We sent a ping and now we must wait for a pong before talking again. if ($response eq "pong") { ## We recieved a pong print "pong\n"; sleep(3); ## Wait just so things to fly by too fast print $socket "ping\n"; ## Now its our turn to talk...say ping print "ping..."; $mode = 2; ## Now that we said ping wait for a pong } } else { ## Just in case some wierd thing happens close($socket); die "Entered invalid mode"; } } else { ## We got an undef and therefore?? the connection was closed. print "Lost connection\n"; last; } } close($socket); exit 0;