pub struct BinaryServer { /* private fields */ }Expand description
A JSON-RPC server that communicates via stdin/stdout.
The server reads line-delimited JSON requests from stdin and writes line-delimited JSON responses to stdout. This makes it easy to integrate with TypeScript or other language frameworks using process spawning.
§Example
use opencore_jsonrpc_rust::server::BinaryServer;
use serde_json::Value;
fn multiply(params: Vec<Value>) -> Result<Value, String> {
if params.len() != 2 {
return Err("Expected 2 parameters".into());
}
let a = params[0].as_f64().ok_or("Invalid number")?;
let b = params[1].as_f64().ok_or("Invalid number")?;
Ok(Value::from(a * b))
}
fn main() {
let mut server = BinaryServer::new();
server.register("multiply", multiply);
server.run();
}Implementations§
Source§impl BinaryServer
impl BinaryServer
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new empty server with no registered handlers.
§Example
use opencore_jsonrpc_rust::server::BinaryServer;
let server = BinaryServer::new();Sourcepub fn register(&mut self, action: &str, handler: Handler)
pub fn register(&mut self, action: &str, handler: Handler)
Registers a handler function for a specific action name.
When a request with the given action is received, the corresponding handler will be invoked with the request parameters.
§Arguments
action- The action name to register (e.g., “sum”, “multiply”)handler- The handler function to invoke for this action
§Example
use opencore_jsonrpc_rust::server::BinaryServer;
use serde_json::Value;
fn echo(params: Vec<Value>) -> Result<Value, String> {
params.first()
.cloned()
.ok_or_else(|| "No parameter provided".into())
}
let mut server = BinaryServer::new();
server.register("echo", echo);Sourcepub fn run(&self)
pub fn run(&self)
Starts the server loop, reading from stdin and writing to stdout.
This method blocks indefinitely, processing requests as they arrive. Each line from stdin should be a valid JSON request. Responses are written as JSON lines to stdout.
§Panics
This method will not panic under normal circumstances. I/O errors are handled gracefully by continuing to the next request.