双向客户端 - 服务器

时间:2013-04-08 11:32:47

标签: perl sockets client-server

有人能指导我在IO :: Socket :: INET中开发的双向客户端 - 服务器脚本发送和接收短信吗? 我需要研究它的流程和工作。 TY。

2 个答案:

答案 0 :(得分:2)

就像任何其他文件句柄一样。

while (<$socket>) {    # Receiving
   print $socket $_;   # Sending
}

答案 1 :(得分:1)

以下是针对上述问题的最简单的解决方案:

服务器脚本

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