Giter VIP home page Giter VIP logo

jsonrpc2-rs's Introduction

jsonrpc2-rs

crates.io

A JSON-RPC 2.0 client/server library in rust.

How to use

Define the structed value types

You should define the types of the follwing three structed values:

For example:

type RequestParams = Vec<u32>;
type ResponseResult = u32;
type ErrorData = String;

Define the handler

You should implement the THandler trait to define the server side logic:

#[async_trait]
pub trait THandler<S, R, E>
where
    S: Serialize,
{
    async fn handle(&self, conn: Arc<JsonRpc2<S, R, E>>, request: Request<S>);
} 

For example:

struct Add {}

#[async_trait]
impl THandler<RequestParams, ResponseResult, ErrorData> for Add {
    async fn handle(
        &self,
        json_rpc2: Arc<JsonRpc2<RequestParams, ResponseResult, ErrorData>>,
        request: Request<RequestParams>,
    ) {
        match request.method.as_str() {
            "add" => {
                let params = request.params.unwrap();
                let add_res: u32 = params.iter().sum();
                let response = Response::new(request.id.unwrap(), Some(add_res), None);
                json_rpc2.response(response).unwrap();
            }

            _ => {
                log::info!("unknow method");
            }
        }
    }
}

Init JSON-RPC server

let addr = "127.0.0.1:9002";
let listener = TcpListener::bind(&addr).await.expect("Can't listen");

if let Ok((stream, _)) = listener.accept().await {
    let server_stream = ServerObjectStream::accept(stream)
        .await
        .expect("cannot generate object stream");
    JsonRpc2::new(Box::new(server_stream), Some(Box::new(Add {}))).await;
}

Init JSON-RPC client

let url = url::Url::parse("ws://127.0.0.1:9002/").unwrap();
let client_stream = ClientObjectStream::connect(url)
    .await
    .expect("cannot generate object stream");

let conn_arc =
    JsonRpc2::<_, ResponseResult, ErrorData>::new(Box::new(client_stream), None).await;

Call the function

match conn_arc.call("add", Some(vec![2u32, 3u32, 4u32])).await {
    Ok(response) => {
        let result = response.result.unwrap();
        assert_eq!(result, 9);
    }
    Err(err) => {
        log::error!("call add error: {}", err);
    }
}

jsonrpc2-rs's People

Contributors

harlanc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.