JSON::RPC2::TwoWay - Transport-independent bidirectional JSON-RPC 2.0


  $rpc = JSON::RPC2::TwoWay->new();
  $rpc->register('ping', \&handle_ping);

  $con = $rpc->newconnection(
    owner => $owner, 
    write => sub { $stream->write(@_) }
  @err = $con->handle($stream->read);
  die $err[-1] if @err;


JSON::RPC2::TwoWay is a base class to implement bidirectional (a.k.a. twoway) communication using JSON-RPC 2.0 remote procedure calls: both sides can operate as Clients and Servers simultaneously. This class is transport-independent.



$rpc = JSON::RPC2::TwoWay->new();

Class method that returns a new JSON::RPC2::TwoWay object.

Valid arguments are:

- debug: print debugging to STDERR
- json: json encoder/decoder object to use. Defaults to JSON::MaybeXS->new().


my $con = $rpc->newconnection(owner => $owner, write = $write);

Creates a JSON::RPC2::TwoWay::Connection with owner $owner and writer $write.

See JSON::RPC2::TwoWay::Connection for details.


$rpc->register('my_method', sub { ... }, option => ... );

Register a new method to be callable. Calls are passed to the callback.

Valid options are:

- by_name

When true the arguments to the method will be passed in as a hashref, otherwise as a arrayref. (default true)

- non_blocking

When true the method callback will receive a callback as its last argument for passing back the results (default false)

- notification

When true the method is a notification and no return value is expected by the caller. (Any returned values will be discarded in the handler.)

- state

When defined must be a string value defining the state the connection (see newconnection) must be in for this call to be accepted.



Unregister a method.


The method callback passed as the second argument of register is called with 2 or 3 arguments: the first argument is the JSON::RPC2::TwoWay::Connection object on which the request came in. The second argument is a arrayref or hashref depending on if the method was registered as by-position or by-name. The third argument, if present is a result callback that needs to be called with the results of the method:

  sub mymethod {
     ($c, $i, $cb) = @_;
     $foo = $i->{foo};

  some time later;

  $cb->("you sent $foo");

If the method callback returns a scalar value the JSON-RPC 2.0 result member value will be a JSON string, number, or null value. If the method returns a hashref the result member value will be an object. If the method returns multiple values or an arrayref the result member value will be an array.



This software has been developed with support from STRATO. In German: Diese Software wurde mit Unterstützung von STRATO entwickelt.


  • Wieger Opmeer <>


This software is copyright (c) 2016-2019 by Wieger Opmeer.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.