perl socket传hash
http://www.perlmonks.org/?node_id=718648# server.pl
use strict;
use warnings;
use Data::Dumper;
use JSON::XS;
use IO::Socket;
use Sys::Hostname;
use constant BUFSIZE => 1024;
my $JSONObject = JSON::XS->new->ascii->pretty->allow_nonref();
my $host = hostname;
my $port = shift || '10280';
my $socket = new IO::Socket(
Domain => PF_INET,
Proto => getprotobyname('tcp'),
LocalAddr => $host,
LocalPort => $port,
Listen => 1, #SOMAXCONN,
#ReuseAddr => SO_REUSEADDR,
) or die $@;
my $buffer;
print "Waiting to do service...\n";
while (my $client = $socket->accept) {
print "Client: ", $client->peerhost, " Connected..\n";
syswrite($client, "Reached Server\n", BUFSIZE);
if (sysread($client, $buffer, BUFSIZE) > 0) {
my @AoH = $JSONObject->decode($buffer);
print "AoH: " . Dumper(@AoH);
}
}
-----------------# client.pl
use strict;
use warnings;
use JSON::XS;
use IO::Socket;
use constant BUFSIZE => 1024;
my $JSONObject = JSON::XS->new->ascii->pretty->allow_nonref();
my @AoH = (
{
husband => "barney",
wife => "betty",
son => "bamm bamm",
},
{
husband => "george",
wife => "jane",
son => "elroy",
},
{
husband => "homer",
wife => "marge",
son => "bart",
},
);
my $host = shift or die "Usage: client.pl host \n";
my $port = shift || '10280';
my $socket = new IO::Socket(
Domain => PF_INET,
PeerAddr => $host,
PeerPort => $port,
Proto => getprotobyname('tcp'),
Timeout=> 60,
) or die $@;
my $buffer;
if (sysread($socket, $buffer, BUFSIZE) > 0) {
syswrite(STDOUT, $buffer);
}
syswrite($socket, $JSONObject->encode(\@AoH), BUFSIZE);
close($socket);
-------------------------
接受中文字符解码:
my $ll =encode("gb2312",decode("utf8",$mm->{$_}));
最简单的json使用
client:
use JSON;
$heap->{json} = JSON->new->ascii;
my $j_param = $heap->{json}->encode(\%color);
$heap->{server}->put($j_param);
server:
my $c_par = from_json($input);
页:
[1]