加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl socket传hash(use Storable)

发布时间:2020-12-16 00:38:11 所属栏目:大数据 来源:网络整理
导读:cpan关于Storable的例子 use Storable qw ( store retrieve freeze thaw dclone ); %color = ( 'Blue' = 0.1 , 'Red' = 0.8 , 'Black' = 0 , 'White' = 1 ); store ( %color , 'mycolors' ) or die "Can't store %a in mycolors!n" ; $colref = retrieve (

cpan关于Storable的例子

        use Storable qw(store retrieve freeze thaw dclone);

        %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);

        store(%color, 'mycolors') or die "Can't store %a in mycolors!n";

        $colref = retrieve('mycolors');
        die "Unable to retrieve from mycolors!n" unless defined $colref;
        printf "Blue is still %lfn", $colref->{'Blue'};

        $colref2 = dclone(%color);

        $str = freeze(%color);
        printf "Serialization of %%color is %d bytes long.n", length($str);
        $colref3 = thaw($str);

用在socket上

client:

#!/usr/bin/perl
use strict;
use IO::Socket;
use Data::Dumper;
use Storable qw(store retrieve freeze thaw dclone);

my $lsocket=&nsock;

my %color = ('Blue' => 0.1,'Red' => 0.8,'Black' => 0,'White' => 1);
my $str = freeze(%color);

print $lsocket $str;

$lsocket->shutdown(1);
while(<$lsocket>){
??????? print "$_";
??}
?

sub nsock(){
??????? return IO::Socket::INET->new(
PeerAddr=>'127.0.0.1',
PeerPort=>'4321',
Proto=>'tcp',
);
}

?

?

-----

server端

#!/usr/bin/perl
use strict;
use IO::Socket;
use Data::Dumper;
use Storable qw(store retrieve freeze thaw dclone);

my $lsocket=IO::Socket::INET->new(
LocalAddr=>'127.0.0.1',
LocalPort=>'4321',
Listen=>SOMAXCONN,
Reuse=>1,
Timeout=>30,
);
#=cut
while(1){
??????? my $tmpsocket = $lsocket->accept;
??????? next unless defined($tmpsocket);
??????? while(<$tmpsocket>){
??????????????? my $colref3 = thaw($_);
??????????????? print Dumper $colref3;
??????? }
??????? $tmpsocket->shutdown(1);
??????? print "end printn";
}
-------

结果:

[root@localhost socket]# perl server.pl
$VAR1 = {
????????? 'Red' => '0.8',
????????? 'Blue' => '0.1',
????????? 'Black' => 0,
????????? 'White' => 1
??????? };
end print

?linux-windows socket传中文字符会出现乱码

今天使用storable又发现一个问题,不知道是不是我哪里出错了

问题描述

my %color = ('Blue' => ‘aa’,'White' => 1);

传这样的hash socket另一端解析不了。

建议使用JSON模块,很简单,还可以处理中文字符问题

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读