通过Perl在Client-Server Scripts之间进行双向通信

时间:2013-04-08 19:45:50

标签: perl sockets network-programming client-server

需求:

  1. s.erver等待连接。
  2. 客户端运行后,通过套接字的连接就会成功开发。
  3. 服务器读取文本文件并将消息发送给客户端。
  4. 客户端收听并打印它。
  5. 客户端读取文本文件将消息(确认)发送到服务器。
  6. 服务器侦听并打印它。

1 个答案:

答案 0 :(得分:7)

以下是上述问题的解决方案:

服务器脚本:

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

客户端脚本:

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