golang 实现

最后更新于:2022-04-02 02:57:28

[TOC] ## 目录 ``` ├── base │ └── struct.go ├── client.go ├── pr │ └── helloword.proto └── server.go ```
base/struct.go ``` package base import ( "context" "grpc/demo/pr" ) type Server struct{} func (s *Server) SayHello(ctx context.Context, in *pr.HelloRequest) (*pr.HelloReply, error) { return &pr.HelloReply{Message: "Hello " + in.Name}, nil } ```

client.go ``` package main import ( "context" "grpc/demo/pr" "log" "google.golang.org/grpc" ) const ( address = "127.0.0.1:50051" ) var input =make(chan string ) func main() { // Set up a connection to the server. conn, err := grpc.Dial(address,grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pr.NewGreeterClient(conn) r, err := c.SayHello(context.Background(), &pr.HelloRequest{Name:"cc"}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.Message) } ```

server.go ``` package main import ( "grpc/demo/base" "grpc/demo/pr" "log" "net" "google.golang.org/grpc" ) const ( port = ":50051" ) func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pr.RegisterGreeterServer(s, &base.Server{}) err = s.Serve(lis) if err != nil { log.Printf("%v",err) } } ```

server.go ``` package main import ( "grpc/demo/base" "grpc/demo/pr" "log" "net" "google.golang.org/grpc" ) const ( port = ":50051" ) func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pr.RegisterGreeterServer(s, &base.Server{}) err = s.Serve(lis) if err != nil { log.Printf("%v",err) } } ```

## proto 转go ``` go mod grpc/demo cd pr protoc --go_out=plugins=grpc:. helloword.proto cd ../ go run server.go go run client.go ```
';