Powered by coANDco UK

Howto program server/client application with Perl

From How2s

Revision as of 08:33, 27 January 2005 by FloH (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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


#!/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;


#!/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;

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