Friday, April 16, 2010

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


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.


Cleint Side:

use IO::Socket;

$sock = new IO::Socket::INET(
PeerAddr => "",
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";
print $sock "exit\n";


Client output

perl ./
MySQLD is now down

Server Side:

use IO::Socket;

$sock = new IO::Socket::INET(
LocalHost => '',
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";
elsif ($line eq "test\n"){
print $client "Received\n";
elsif ($line eq "shutdown\n"){
print $client "MySQLD is now down\n";


Server output
perl ./
Client sent exit

Start the and then run the

Hope this example helps someone! ;-)

Best wishes,