6 releases

0.2.1 Nov 10, 2024
0.2.0 Nov 10, 2024
0.1.3 Sep 10, 2024

#1014 in Network programming

Download history 171/week @ 2024-09-01 670/week @ 2024-09-08 49/week @ 2024-09-15 36/week @ 2024-09-22 14/week @ 2024-09-29 1/week @ 2024-10-13 4/week @ 2024-11-03 361/week @ 2024-11-10

365 downloads per month
Used in 3 crates

MIT license

29KB
528 lines

jsonlrpc

jsonlrpc Documentation Actions Status License

A JSON-RPC 2.0 library that streams JSON objects in JSON Lines format.

Examples

RPC client:

use std::net::TcpStream;
use jsonlrpc::{RpcClient, RequestId, RequestObject, ResponseObject, JsonRpcVersion};

// Connect to a JSON-RPC server.
let server_addr = spawn_rpc_server_thread(); // See below
let socket = TcpStream::connect(server_addr).expect("failed to connect to server");
let mut client = RpcClient::new(socket);

// Send a request to the server.
let request = RequestObject {
    jsonrpc: JsonRpcVersion::V2,
    id: Some(RequestId::Number(1)),
    method: "foo".to_string(),
    params: None,
};
let response = client.call(&request).expect("failed to RPC call");

// Check the response.
let Some(ResponseObject::Ok { result, id, .. }) = response else {
    panic!("expected ok response, got notification or err response")
};
assert_eq!(id, RequestId::Number(1));

RPC server:

use std::net::{SocketAddr, TcpListener};
use jsonlrpc::{JsonlStream, JsonRpcVersion, RequestObject, ResponseObject};

fn spawn_server_thread() -> SocketAddr {
    let listener = TcpListener::bind("127.0.0.1:0").expect("failed to bind to address");
    let addr = listener.local_addr().expect("failed to get local address");

    std::thread::spawn(move || {
        for stream in listener.incoming() {
            let stream = stream.expect("failed to accept incoming connection");
            let mut stream = JsonlStream::new(stream);
            std::thread::spawn(move || {
                let request: RequestObject = stream.read_value().expect("failed to read request");
                let response = ResponseObject::Ok {
                    jsonrpc: JsonRpcVersion::V2,
                    id: request.id.expect("expected request id"),
                    result: serde_json::Value::String(request.method),
                };
                stream.write_value(&response).expect("failed to write response");
            });
        }
    });

    addr
}

Dependencies

~0.7–1.6MB
~34K SLoC