2010-05-13 42 views
4

在套接字中我编写了客户端服务器程序。首先我试图发送正常的字符串,它发送正常。之后,我尝试将哈希和数组值从客户端发送到服务器和服务器到客户端。当我使用Dumper打印这些值时,它只给出参考值。我应该怎么做才能获得客户端服务器的实际值?如何通过套接字共享Perl数据结构?

服务器程序:

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

my %hash = ("name" => "pavunkumar " , "age" => 20) ; 
my $new = \%hash ; 
#Turn on System variable for Buffering output 
$| = 1; 
# Creating a a new socket 
my $socket= 
IO::Socket::INET->new(LocalPort=>5000,Proto=>'tcp',Localhost => 
     'localhost','Listen' => 5 , 'Reuse' => 1); 
die "could not create $! \n" unless ($socket); 
     print "\nUDPServer Waiting port 5000\n"; 
     my $new_sock = $socket->accept(); 
     my $host = $new_sock->peerhost(); 
     while(<$new_sock>) 
     { 
     #my $line = <$new_sock>; 
     print Dumper "$host $_"; 
     print $new_sock $new . "\n"; 
     } 
     print "$host is closed \n" ; 

客户端程序

use IO::Socket;        
use Data::Dumper ;        
use warnings ;         
use strict ;         

my %hash = ("file" =>"log.txt" , size => "1000kb") ; 

my $ref = \%hash ; 


# This client for connecting the specified below address and port 
# INET function will create the socket file and establish the connection with 
# server 

my $port = shift || 5000 ; 
my $host = shift || 'localhost'; 
my $recv_data ; 
my $send_data; 
my $socket = new IO::Socket::INET (
            PeerAddr => $host , 
            PeerPort => $port , 
            Proto => 'tcp',) 

or die "Couldn't connect to Server\n"; 
while (1) 
{ 
     my $line = <stdin> ; 
     print $socket $ref."\n"; 
     if ($line = <$socket>) 
     { 
       print Dumper $line ; 
     } 
     else 
     { 
       print "Server is closed \n"; 
       last ; 
     } 

} 

我已经给约我在做什么我的示例程序。任何人都可以告诉我我在做什么 这段代码错了吗?我需要做什么来访问哈希值?

回答

8

当你说

print $ref; 

,你在部分指示Perl中把$ref成字符串(因为只有字符串可以print版)。事实证明,默认情况下引用不会变成非常有用的字符串。

您需要打开$ref成可以通过线路发送,然后解码在对方取回数据一个字符串。这个过程被称为“序列化”。 Data::Dumper的输出实际上是其参数的有效序列化,但Perl中的基本序列化模块是Storable

在程序上,可以说[1]在一侧

use Storable qw(nfreeze); # nfreeze rather than freeze because 
          # we want a network-portable string 
... 
print nfreeze($ref); 

use Storable qw(thaw); 
... 
my $ref = thaw($line); 
在另一

还有一个面向对象的接口;阅读Storable文档以获取更多信息。

[1]:注意yaddayaddas。这是不完整的代码,只是说明了与您的代码的主要区别。

+2

很好的答案。值得强调的是,您使用了'nfreeze'(而不是'freeze'),这有助于使可存储的编码数据更加便携。 – daotoad 2010-05-13 05:37:21

+0

谢谢,完成。 – darch 2010-05-13 06:24:12

5

问题是你发送的是对数据的引用,而不是数据本身。你需要以某种方式序列化数据。 JSON是一个非常简单的方法来做到这一点。还有YAML

相关问题