Powered by coANDco UK

Howto program server/client application with Perl

From How2s

This How2 gives you an example for a typcial client/server application written in Perl.

Server:

#!/opt/bin/perl5 -w
# Server Application 

use strict;
use Socket;

my $port = 1302;
my $proto = getprotobyname('tcp');

# create a socket, make it reusable
socket(SERVER, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR,1) or die "setscok: $!";

# grab port on this machine
my $paddr = sockaddr_in($port, INADDR_ANY); 

# bind to a port then listen
bind(SERVER, $paddr) or die "bind: $!";
listen(SERVER, SOMAXCONN) or die "listen: $!";
print "SERVER started on port $port";
 
# accepting a connection
my $client_addr;

while ($client_addr = accept(CLIENT, SERVER))
{
       #find out who connected
       my ($client_port, $client_ip) = sockaddr_in($client_addr);
       my $client_ipnum = inet_ntoa($client_ip);
       my $client_host = gethostbyaddr($client_ip, AF_INET);
       print "got a connection fom $client_host","[$client_ipnum]";

       print CLIENT "\r\n*********************\r\n";
       print CLIENT "Welcome!\r\n";
       print CLIENT "*********************\r\n";
       close CLIENT;
}


Client:

#!/opt/bin/perl5 -w
# Client Application 
use IO::Socket::INET;
print ">> Client Program << \n";

# create a new Socket
$MySocket = new IO::Socket::INET->new(PeerPort=>1234,Proto=>'udp',PeerAddr=>'localhost');

# send message
$def_msg="Enter message to send to the server: ";
print $def_msg;

while($msg=<STDIN>)
{
       chomp $msg;
       if($msg ne )
       {
               print "\nSending message '",$msg,"'";
               if($MySocket->send($msg))
               {
                       print ".....<done>\n";
                       print $def_msg;
               }
       }
       else
       {
               #Send an empty message to server and exit
               $MySocket->send();
               exit 1;
       }
}
Please check out our sponsor, thanks to whom How2s.org is FREE: