Sahej Narang
Sahej Narang

Reputation: 359

2 way communication between Client-Server Scripts through Perl

REQUIREMENTS:

  1. The s.erver waits for connection.
  2. Once the client runs, the connection through the socket is developed successfully.
  3. The Server reads a text file and sends the message to the Client.
  4. The Client listens to it and prints it.
  5. The Client reads a text file sends the message (acknowledgement) to the Server.
  6. The Server listens to it and prints it.

Upvotes: 0

Views: 2895

Answers (1)

Sahej Narang
Sahej Narang

Reputation: 359

Here is the solution to the above mentioned problem:

SERVER SCRIPT:

#!/usr/bin/perl

use strict;
use warnings;
use IO::Socket::INET;

my $socket;
my  $clientsocket;
my $serverdata;
my $clientdata;

$socket = new IO::Socket::INET (
    LocalHost => '127.0.0.1',
    LocalPort => '0155',
    Proto => 'tcp',
    Listen => 1,
    Reuse => 1
) or die "Oops: $! \n";
print "Waiting for the Client.\n";


$clientsocket = $socket->accept();

print   "Connected from : ", $clientsocket->peerhost();     # Display messages
print   ", Port : ", $clientsocket->peerport(), "\n";

# Write some data to the client  
$serverdata = "This is the Server speaking :)\n";
print $clientsocket "$serverdata \n";

# read the data from the client
$clientdata = <$clientsocket>;
print "Message received from Client : $clientdata\n";

$socket->close();  

CLIENT SCRIPT:

#!/usr/bin/perl

use strict;
use warnings;
use IO::Socket::INET;

my $socket;
my $serverdata;
my $clientdata;

$socket = new IO::Socket::INET (
  PeerHost => '127.0.0.1',
  PeerPort => '0155',
  Proto => 'tcp',
) or die "$!\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 = "This is the Client speaking :)";
print $socket "$clientdata \n";

$socket->close();

Upvotes: 7

Related Questions