在套接字中,我编写了客户端服务器程序.首先,我尝试发送正常的字符串,它发送正常.之后我尝试将哈希值和数组值从客户端发送到服务器和服务器到客户端.当我使用Dumper打印值时,它只给我参考值.我该怎么做才能在客户端服务器中获取实际值?
服务器程序:
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 =; print $socket $ref."\n"; if ( $line = <$socket> ) { print Dumper $line ; } else { print "Server is closed \n"; last ; } }
我已经提供了关于我正在做什么的示例程序.谁能告诉我这段代码中我做错了什么?我需要做什么才能访问哈希值?
当你说
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);
在另一.
还有一个OO接口; 阅读Storable
文档以获取更多信息.
[1]:注意yaddayaddas.这是不完整的代码,仅仅说明了与代码的主要区别.
问题是您正在发送对数据的引用,而不是数据本身.您需要以某种方式序列化数据.JSON是一种非常简单的方法.还有YAML.