Perl 套接字发送哈希 [英] Perl socket sending hash
问题描述
我正在尝试在 Perl 中创建一个套接字客户端.服务器端是一个运行在本地主机上的C程序.
I am trying to create a socket client in Perl. The server side is a C program running on the local host.
我必须通过套接字发送一个哈希值.这是我正在使用的一段代码.
I have to send a hash over the socket. Here is the piece of code I am using.
sub applyGlobalConfig {
my ($globalConfig, $ignoreData) = @_;
my $socket = IO::Socket::INET->new(PeerAddr => $PEER_HOST,
PeerPort => $PEER_PORT,
Proto => "tcp",
Type => SOCK_STREAM)
or die "Couldn't connect to $PEER_HOST:$PEER_PORT : $@\n";
my $reconfigResult;
print $socket "$113\n";
close($socket);
unless ($reconfigResult) {
return 0;
}
return ERR_NULL;
}
现在,我的问题是,$globalConfig
将包含一个散列引用,我想通过套接字发送它.我无法弄清楚.我用谷歌搜索并找到了一些对 Dumper 的参考,但不太明白.如何发送散列?
Now, the question I have is, the $globalConfig
will contain a hash reference, and I want to send this over a socket. I am unable figure out. I googled and found some reference to Dumper but couldn’t understand much. How do I send the hash over?
推荐答案
我更喜欢使用 Storable 模块.示例:
I'd prefer to use Storable module for this. Example:
接收端:
use strict;
use IO::Socket::INET;
use Storable;
use Data::Dumper;
my $sock = IO::Socket::INET->new(Listen => 5, LocalAddr => 'host',
LocalPort => 9000, Proto => 'tcp');
while( my $s = $sock->accept ) {
my $struct = Storable::fd_retrieve($s);
print Dumper($struct);
}
发送端:
use strict;
use IO::Socket::INET;
use Storable;
my $sock = IO::Socket::INET->new(PeerAddr => 'host', PeerPort => 9000,
Type => SOCK_STREAM, Proto => 'tcp') || die "Fail: $!";
my $struct = {
a => 1,
b => [2,3,4]
};
Storable::nstore_fd($struct, $sock);
通过从 i386 Linux 发送到 amd64 FreeBSD 进行测试.
Tested by sending from i386 Linux to amd64 FreeBSD.
您也可以使用 Data::Dumper 从哈希中生成字符串,然后通过网络发送,但它的方法又脏又臭.
Also you can use Data::Dumper to make string from hash and then send over network but its dirty and buggy method.
UPD:
但是,我正在努力如何将 perl 端的哈希值转换为由空格分隔的字符串.
But, I am struggling how to convert the values in the hash on perl side to a string separated by space.
尝试使用 join/map 组合:
Try to use join/map combination:
my $serialized = join("\n", map { "$_ ".$struct->{$_} } keys %$struct)."\n";
可能在 C 端更容易使用以空字符结尾的字符串:
Probably on C side its easier to use null-terminated string:
my $keyvalue_count = scalar keys(%$struct);
my $serialized = join("\0", map { "$_\0".$struct->{$_} } keys %$struct)."\0";
在这个简单的例子中,我更喜欢使用最后一个变体,因为它是 C 原生的.
In this simple case i'd prefer to use last variant since its native to C.
这篇关于Perl 套接字发送哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!