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
Subscribe to:
Post Comments (Atom)
4 comments:
I'm constantly amazed by how bad perls syntax is, I cannot understand why people like it... $_ as a variable name? seriously?
thanks for your help and get good idea from your suggestion
THANK YOU.....i was having the hardest time finding a tutorial on how to have 2 way communication between sockets...This was great...
wonderful information, I had come to know about your blog from my friend nandu , hyderabad,i have read atleast 7 posts of yours by now, and let me tell you, your website gives the best and the most interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new posts, once again hats off to you! Thanks a ton once again, Regards, QA online trainingamong the QA in Hyderabad. Classroom Training in Hyderabad India
Post a Comment