Friday, April 16, 2010

Perl IO::Socket, how to make them talk on both ends Cient/Server

Hi,

Was exploring IO::Socket for some test automation I'm looking at doing.

I found a lot of examples on talking to the server side, but not really any good ones on how to recieve and process on the client side what the sever sent in response.

After playing with it for a while today, I finially got the basics working and wanted to share incase others are wanting to deal with 2 way comunication. The main thing to remember is the $_ and what it is used for.

Examples:

Cleint Side:
-----------

use IO::Socket;

$sock = new IO::Socket::INET(
PeerAddr => "127.0.0.1",
PeerPort => 1234,
Proto => 'tcp') || die "Error creating socket: $!";

print $sock "test\n"; #test coms and start a chat

while ( <$sock> ){
print "$_"; # The servers reponse will be in $_
if ($_ ne "MySQLD is now down\n"){
print $sock "shutdown\n";
}
else{
print $sock "exit\n";
}
}

close($sock);


-------------
Client output
-------------

perl ./client.pl
Received
MySQLD is now down


Server Side:
------------

use IO::Socket;

$sock = new IO::Socket::INET(
LocalHost => '127.0.0.1',
LocalPort => 1234,
Listen => 1,
Reuse => 1,
Proto => 'tcp') || die "Error creating socket: $!
";

$client = $sock->accept();

while($line = <$client>) {
print $line;
if ($line eq "exit\n"){
print "Client sent exit\n";
close($client);
}
elsif ($line eq "test\n"){
print $client "Received\n";
}
elsif ($line eq "shutdown\n"){
print $client "MySQLD is now down\n";
}
}

close($sock);

-------------
Server output
-------------
perl ./server.pl
test
shutdown
exit
Client sent exit


Start the server.pl and then run the client.pl

Hope this example helps someone! ;-)

Best wishes,
/Jeb