在套接字中我编写了客户端服务器程序。首先,我尝试在其中发送普通字符串,它发送得很好。之后,我尝试将哈希值和数组值从客户端发送到服务器,再将服务器发送到客户端。当我使用 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 = <stdin> ;
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 http://perldoc.perl.org/Storable.html.
从程序上来说,你可以说[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。这是不完整的代码,仅说明与您的代码的主要区别。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)