Server

The main function activates a logger and spawns a worker. Then, we extract the ADDRESS environment variable to use this address value to bind a socket of a server. Loot at the following code:

fn main() -> Result<(), Error> {
env_logger::init();
let tx = spawn_worker()?;
let addr: SocketAddr = env::var("ADDRESS")?.parse()?;
let mut io = IoHandler::default();
let sender = Mutex::new(tx.clone());
io.add_method(START_ROLL_CALL, move |_| {
trace!("START_ROLL_CALL");
let tx = sender
.lock()
.map_err(to_internal)?;
tx.send(Action::StartRollCall)
.map_err(to_internal)
.map(|_| Value::Bool(true))
});
let sender = Mutex::new(tx.clone());
io.add_method(MARK_ITSELF, move |_| {
trace!("MARK_ITSELF");
let tx = sender
.lock()
.map_err(to_internal)?;
tx.send(Action::MarkItself)
.map_err(to_internal)
.map(|_| Value::Bool(true))
});
let server = ServerBuilder::new(io).start_http(&addr)?;
Ok(server.wait())
}

To implement JSON-RPC methods, we use the IoHandler struct. It has the add_method method, which expects the name of the method and needs a closure with an implementation of this method.

We added two methods, start_roll_call and mark_itself, using constants as names for these methods. The implementation of these methods is simple: we only prepare the corresponding Action messages and send them to the worker's thread.

The JSON-RPC method implementation has to return the Result<Value, ServerError> value. To convert any other errors to ServerError we use the following function:

fn to_internal<E: fmt::Display>(err: E) -> ServerError {
error!("Error: {}", err);
ServerError::internal_error()
}

The function only prints the current error message and creates an error with the InternalError code using the internal_error method of the ServerError type.

At the end of main function, we create a new ServerBuilder instance with the created IoHandler and start the HTTP server to listen for JSON-RPC requests with the start_http server.

Now we can start a ring of services to test it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.147.77