Skip to content

Commit

Permalink
chore(examples): add helloworld-client-blocking (#179)
Browse files Browse the repository at this point in the history
Add an example of using a tonic client in a synchronous environment.
  • Loading branch information
bmwill authored and LucioFranco committed Dec 12, 2019
1 parent 8f1a252 commit f096a23
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
4 changes: 4 additions & 0 deletions tonic-examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ path = "src/helloworld/server.rs"
name = "helloworld-client"
path = "src/helloworld/client.rs"

[[bin]]
name = "helloworld-client-blocking"
path = "src/helloworld/client-blocking.rs"

[[bin]]
name = "routeguide-server"
path = "src/routeguide/server.rs"
Expand Down
56 changes: 56 additions & 0 deletions tonic-examples/src/helloworld/client-blocking.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use tokio::runtime::{Builder, Runtime};

pub mod hello_world {
tonic::include_proto!("helloworld");
}

use hello_world::{greeter_client::GreeterClient, HelloReply, HelloRequest};

type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
type Result<T, E = StdError> = ::std::result::Result<T, E>;

// The order of the fields in this struct is important. The runtime must be the first field and the
// client must be the last field so that when `BlockingClient` is dropped the client is dropped
// before the runtime. Not doing this will result in a deadlock when dropped.
struct BlockingClient {
rt: Runtime,
client: GreeterClient<tonic::transport::Channel>,
}

impl BlockingClient {
pub fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: std::convert::TryInto<tonic::transport::Endpoint>,
D::Error: Into<StdError>,
{
let mut rt = Builder::new()
.basic_scheduler()
.enable_all()
.build()
.unwrap();
let client = rt.block_on(GreeterClient::connect(dst))?;

Ok(Self { rt, client })
}

pub fn say_hello(
&mut self,
request: impl tonic::IntoRequest<HelloRequest>,
) -> Result<tonic::Response<HelloReply>, tonic::Status> {
self.rt.block_on(self.client.say_hello(request))
}
}

fn main() -> Result<()> {
let mut client = BlockingClient::connect("http://[::1]:50051")?;

let request = tonic::Request::new(HelloRequest {
name: "Tonic".into(),
});

let response = client.say_hello(request)?;

println!("RESPONSE={:?}", response);

Ok(())
}

0 comments on commit f096a23

Please sign in to comment.