linux poison RSS
linux poison Email

Perl Script: Simple Network Programming (Client - Server Application)

A network socket is an endpoint of an inter-process communication flow across a computer network. Today, most communication between computers is based on the Internet Protocol; therefore most network sockets are Internet sockets.

In Perl, IO::Socket::INET provides an object interface to creating and using sockets in the AF_INET domain. It is built upon the IO::Socket interface and inherits all the methods defined by IO::Socket.

Below is a simple server created using Perl IO::Socket::INET module

Source: server.pl
#!/usr/bin/perl

use IO::Socket::INET;

$socket = new IO::Socket::INET (
    LocalHost => '127.0.0.1',
    LocalPort => '40000',
    Proto => 'tcp',
    Listen => 10,
    Reuse => 1
) or die "Oops: $! \n";
print "Server is up and running ... \n";

while (1) {
  $clientsocket = $socket->accept();
 
  print " **** New Client Connected **** \n ";
 
  # Write some data to the client 
  $serverdata = "This is server speaking ...";
  print $clientsocket "$serverdata \n";
 
  # read the data from the client
  $clientdata = <$clientsocket>;
  print "Message received from Client : $clientdata\n";

 
$socket->close(); 

Below is a simple client created using Perl IO::Socket::INET module which connects to the server and sends-receive some data.

Source: client.pl
#!/usr/bin/perl

use IO::Socket::INET;

$socket = new IO::Socket::INET (
  PeerHost => '127.0.0.1',
  PeerPort => '40000',
  Proto => 'tcp',
) or die "Oops : $!\n";

print "Connected to the server.\n";

# read the message sent by server.
$serverdata = <$socket>;
print "Message from Server : $serverdata \n";

# Send some message to server.
$clientdata = ".. ok, this is client speaking ...";
print $socket "$clientdata \n";

$socket->close();

output: perl server.pl
Server is up and running ...
 **** New Client Connected ****
 Message received from Client : .. ok, this is client speaking ...

output: perl client.pl

Connected to the server.
Message from Server : This is server speaking ...





0 comments:

Post a Comment

Related Posts with Thumbnails