=item packstring => $format, $data
An octet string prefixed with an encoded length. The encoding C<$format>
uses the same format as a Perl C<pack> format, but must specify a single
integer only (only one of C<cCsSlLqQiInNvVjJw> is allowed, plus an
optional C<!>, C<< < >> or C<< > >> modifier).
=cut
register_write_type packstring => sub {
my ($self, $format, $string) = @_;
pack "$format/a*", $string
};
=item json => $array_or_hashref
Encodes the given hash or array reference into a JSON object. Unless you
provide your own JSON object, this means it will be encoded to JSON text
in UTF-8.
JSON objects (and arrays) are self-delimiting, so you can write JSON at
one end of a handle and read them at the other end without using any
additional framing.
The generated JSON text is guaranteed not to contain any newlines: While
this module doesn't need delimiters after or between JSON texts to be
able to read them, many other languages depend on that.
A simple RPC protocol that interoperates easily with others is to send
JSON arrays (or objects, although arrays are usually the better choice as
they mimic how function argument passing works) and a newline after each
JSON text:
$handle->push_write (json => ["method", "arg1", "arg2"]); # whatever
$handle->push_write ("\012");
An AnyEvent::Handle receiver would simply use the C<json> read type and
rely on the fact that the newline will be skipped as leading whitespace:
$handle->push_read (json => sub { my $array = $_[1]; ... });
Other languages could read single lines terminated by a newline and pass
this line into their JSON decoder of choice.
=cut
register_write_type json => sub {
my ($self, $ref) = @_;
require JSON;
$self->{json} ? $self->{json}->encode ($ref)
: JSON::encode_json ($ref)
};
=item storable => $reference
Freezes the given reference using L<Storable> and writes it to the
handle. Uses the C<nfreeze> format.
=cut
register_write_type storable => sub {
my ($self, $ref) = @_;
require Storable;
pack "w/a*", Storable::nfreeze ($ref)
};
=back
=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args)
This function (not method) lets you add your own types to C<push_write>.
Whenever the given C<type> is used, C<push_write> will invoke the code
reference with the handle object and the remaining arguments.
The code reference is supposed to return a single octet string that will
be appended to the write buffer.
Note that this is a function, and all types registered this way will be
global, so try to use unique names.
=cut
#############################################################################
=back
=head2 READ QUEUE
AnyEvent::Handle manages two queues per handle, one for writing and one
for reading.
The read queue is more complex than the write queue. It can be used in two
ways, the "simple" way, using only C<on_read> and the "complex" way, using
a queue.
=6= |