1 use futures::stream::TryStreamExt; 2 use std::{ 3 path::Path, 4 pin::Pin, 5 task::{Context, Poll}, 6 }; 7 use tokio::{ 8 io::{AsyncRead, AsyncWrite}, 9 net::UnixListener, 10 }; 11 use tonic::{ 12 transport::{server::Connected, Server}, 13 Request, Response, Status, 14 }; 15 16 pub mod hello_world { 17 tonic::include_proto!("helloworld"); 18 } 19 20 use hello_world::{ 21 greeter_server::{Greeter, GreeterServer}, 22 HelloReply, HelloRequest, 23 }; 24 25 #[derive(Default)] 26 pub struct MyGreeter {} 27 28 #[tonic::async_trait] 29 impl Greeter for MyGreeter { 30 async fn say_hello( 31 &self, 32 request: Request<HelloRequest>, 33 ) -> Result<Response<HelloReply>, Status> { 34 println!("Got a request: {:?}", request); 35 36 let reply = hello_world::HelloReply { 37 message: format!("Hello {}!", request.into_inner().name), 38 }; 39 Ok(Response::new(reply)) 40 } 41 } 42 43 #[tokio::main] 44 async fn main() -> Result<(), Box<dyn std::error::Error>> { 45 let path = "/tmp/tonic/helloworld"; 46 47 tokio::fs::create_dir_all(Path::new(path).parent().unwrap()).await?; 48 49 let mut uds = UnixListener::bind(path)?; 50 51 let greeter = MyGreeter::default(); 52 53 Server::builder() 54 .add_service(GreeterServer::new(greeter)) 55 .serve_with_incoming(uds.incoming().map_ok(UnixStream)) 56 .await?; 57 58 Ok(()) 59 } 60 61 #[derive(Debug)] 62 struct UnixStream(tokio::net::UnixStream); 63 64 impl Connected for UnixStream {} 65 66 impl AsyncRead for UnixStream { 67 fn poll_read( 68 mut self: Pin<&mut Self>, 69 cx: &mut Context<'_>, 70 buf: &mut [u8], 71 ) -> Poll<std::io::Result<usize>> { 72 Pin::new(&mut self.0).poll_read(cx, buf) 73 } 74 } 75 76 impl AsyncWrite for UnixStream { 77 fn poll_write( 78 mut self: Pin<&mut Self>, 79 cx: &mut Context<'_>, 80 buf: &[u8], 81 ) -> Poll<std::io::Result<usize>> { 82 Pin::new(&mut self.0).poll_write(cx, buf) 83 } 84 85 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> { 86 Pin::new(&mut self.0).poll_flush(cx) 87 } 88 89 fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> { 90 Pin::new(&mut self.0).poll_shutdown(cx) 91 } 92 } 93