Expand description
A JSON RPC protocol for the tokio framework.
This implements the handling of the
JSON RPC 2.0 specification. The low-level parts are in
the message
and the codec
modules. The first
draft of the higher-lever API is in the endpoint
module. Some helpers
to compose the server part is in the server
module.
§Examples
A skeleton of reading messages from the other side, mapping them to answers and sending them back.
let mut core = Core::new().unwrap();
let handle = core.handle();
let listener = TcpListener::bind(&"127.0.0.1:2345".parse().unwrap(), &handle).unwrap();
let connections = listener.incoming();
let service = connections.for_each(|(stream, _)| {
let messages = stream.framed(LineCodec::new());
let (write, read) = messages.split();
let answers = read.filter_map(|message| {
match message {
_ => unimplemented!(),
}
});
handle.spawn(write.send_all(answers).map(|_| ()).map_err(|_| ()));
Ok(())
});
Provide a server that greets through an RPC.
let mut core = Core::new().unwrap();
let handle = core.handle();
let listener = TcpListener::bind(&"127.0.0.1:2346".parse().unwrap(), &handle).unwrap();
struct UselessServer;
impl Server for UselessServer {
type Success = String;
type RpcCallResult = Result<String, RpcError>;
type NotificationResult = Result<(), ()>;
fn rpc(&self,
ctl: &ServerCtl,
method: &str,
_params: &Option<Value>)
-> Option<Self::RpcCallResult> {
match method {
// Accept a hello message and finish the greeting
"hello" => Some(Ok("world".to_owned())),
// When the other side says bye, terminate the connection
"bye" => {
ctl.terminate();
Some(Ok("bye".to_owned()))
},
_ => None
}
}
}
let connections = listener.incoming().for_each(|(stream, _)| {
// Greet every new connection
let (client, _) = Endpoint::new(stream.framed(LineCodec::new()), UselessServer)
.start(&handle);
let notified = client.notify("hello".to_owned(), None)
.map(|_| ())
.map_err(|_| ());
handle.spawn(notified);
Ok(())
});
core.run(connections).unwrap();
Re-exports§
pub use codec::Boundary as BoundaryCodec;
pub use codec::Line as LineCodec;
pub use endpoint::Client;
pub use endpoint::Endpoint;
pub use endpoint::ServerCtl;
pub use message::Message;
pub use message::Parsed;
pub use message::RpcError;
pub use server::Server;
Modules§
- codec
- The codecs to encode and decode messages from a stream of bytes.
- endpoint
- The endpoint of the JSON RPC connection.
- macro_
exports - This contains some reexports so macros can find them.
- message
- JSON-RPC 2.0 messages.
- server
- The
Server
trait and helpers.
Macros§
- jsonrpc_
params - Parses the parameters of an RPC or a notification.