tower-rs / tower-grpc

A gRPC client & server implementation.
MIT License
562 stars 73 forks source link

How to write codes in the server when the proto file has more than one services ? #200

Open najcit opened 5 years ago

najcit commented 5 years ago

the content of the proto file:

syntax = "proto3"; package helloworld;

// The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} }

// The request message containing the user's name. message HelloRequest { string name = 1; }

// The response message containing the greetings message HelloReply { string message = 1; } service Talk { rpc TalkSomething (TalkRequest) returns (TalkReply) {} }

message TalkRequest { string name = 1; }

message TalkReply { string message = 1; }

the codes of the server.rs file: let new_service = server::GreeterServer::new(Greet);

let mut server = Server::new(new_service);

let http = Http::new().http2_only(true).clone();

let addr = "[::1]:50051".parse().unwrap();
let bind = TcpListener::bind(&addr).expect("bind");

let serve = bind
    .incoming()
    .for_each(move |sock| {
        if let Err(e) = sock.set_nodelay(true) {
            return Err(e);
        }

        let serve = server.serve_with(sock, http.clone());
        tokio::spawn(serve.map_err(|e| error!("hyper error: {:?}", e)));

        Ok(())
    })
    .map_err(|e| eprintln!("accept error: {}", e));

tokio::run(serve)

how to modify these code ? thank you!!!

davidvartan commented 5 years ago

This looks to be unimplemented at the moment (see: https://github.com/tower-rs/tower-grpc/issues/2) However, it's easy enough to use tokio to ::spawn two services on different ports for the time being.

LucioFranco commented 5 years ago

What @davidvartan suggested works, there are ways you can manually build a router to serve both on the same socket. This would require you to detect the incoming path. Mostly likely need to write some custom services like so https://github.com/tower-rs/tower-hyper/blob/master/examples/server.rs#L41. This is roughly what tower-grpc-build does but you can wrap it. Then dispatch the call based on the incoming path.

najcit commented 5 years ago

ok, I will try it in the next day by using your idea.