ZMQ::Serializer - Serialization Support
use ZMQ; use ZMQ::Serializer; use JSON (); ZMQ::register_read_type(json => \&JSON::decode_json); ZMQ::register_write_type(json => \&JSON::encode_json); my $sock = $ctx->socket( ... ); $sock->sendmsg_as( json => $payload ); my $payload = $sock->recvmsg_as( 'json' );
You can add a simple serialization/deserialization mechanism to ZMQ by enabling this module.
To enable serialization, you must load ZMQ::Serializer:
use ZMQ; use ZMQ::Serializer;
This will add ZMQ::Socket::sendmsg_as() and ZMQ::Socket::recvmsg_as methods.
ZMQ::Socket::sendmsg_as()
ZMQ::Socket::recvmsg_as
You also need to tell it how/what to serialize/deserialize. To do this, use register_write_type() to register a name and an associated callback to serialize the data. For example, for JSON we do the following (this is already done for you in ZMQ.pm if you have JSON.pm installed):
register_write_type()
use JSON (); ZMQ::Serializer::register_write_type('json' => \&JSON::encode_json); ZMQ::Serializer::register_read_type('json' => \&JSON::decode_json);
Then you can use sendmsg_as() and recvmsg_as() to specify the serialization type as the first argument:
sendmsg_as()
recvmsg_as()
my $ctxt = ZMQ::Context->new(); my $sock = $ctxt->socket( ZMQ_REQ ); $sock->sendmsg_as( json => $complex_perl_data_structure );
The otherside will receive a JSON encoded data. The receivind side can be written as:
my $ctxt = ZMQ::Context->new(); my $sock = $ctxt->socket( ZMQ_REP ); my $complex_perl_data_structure = $sock->recvmsg_as( 'json' );
No serializers are loaded by default.
Register a read callback for a given $name. This is used in recvmsg_as(). The callback receives the data received from the socket.
$name
Register a write callback for a given $name. This is used in sendmsg_as() The callback receives the Perl structure given to sendmsg_as()
Encodes $payload according to the serializer specified by $type, and enqueues a new message to be sent. $payload should be whatever the serializer understands.
$payload
$type
Receives a new message from the queue, and decodes the payload in the received message using the deserializer specified by $type.
To install ZMQ, copy and paste the appropriate command in to your terminal.
cpanm
cpanm ZMQ
CPAN shell
perl -MCPAN -e shell install ZMQ
For more information on module installation, please visit the detailed CPAN module installation guide.