准备环境
go get google.golang.org/grpc go get google.golang.org/protobuf
代码实现
新增 chat/chat.proto 文件:
syntax = "proto3"; package template; option go_package = "../chat"; message Message{ string body = 1; } service ChatService{ rpc SayHello(Message) returns (Message){} rpc BroadcastMessage2(Message) returns (Message) {} }
命令生成pb.go
protoc --go_out=plugins=grpc:chat ./chat/chat.proto
编写chat 服务文件 chat.go:
package chat import ( "context" "log" ) type Server struct { } func (receiver \*Server) SayHello(ctx context.Context, in \*Message) (*Message, error) { log.Printf("Receive message body from client: %s", in.Body) return &Message{Body: "Hello From the Server!"}, nil } func (receiver \*Server) Test(ctx context.Context, in \*Message) (*Message, error) { log.Printf("test new message from a client: %s", in.Body) return &Message{Body: "test message!"}, nil }
编写grpc-server服务端:
package main import ( "fmt" "google.golang.org/grpc" "grpc-study/chat" "log" "net" ) func main() { fmt.Println("Go gRPC Beginners Tutorial!") listen, err := net.Listen("tcp", ":9000") if err != nil { log.Fatalf("failed to listen: %v", err) } grpcServer := grpc.NewServer() s := chat.Server{} chat.RegisterChatServiceServer(grpcServer, &s) if err := grpcServer.Serve(listen); err != nil { log.Fatalf("failed to serve: %s", err) } }
grpc-client 客户端调用
package main import ( "context" "google.golang.org/grpc" "grpc-study/chat" "log" "time" ) func main() { var conn *grpc.ClientConn conn, err := grpc.Dial(":9000", grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %s \\n", err) } defer conn.Close() c := chat.NewChatServiceClient(conn) for true { response, err := c.SayHello(context.Background(), &chat.Message{Body: "66666"}) if err != nil { log.Fatalf("Error when calling SayHello: %s", err) } log.Printf("Response from server: %s", response.Body) broadcastMessage, err := c.Test(context.Background(), &chat.Message{Body: "123"}) if err != nil { log.Fatalf("Error when calling Broadcast Message: %s", err) } log.Printf("Response from server: %s", broadcastMessage.Body) time.Sleep(1*time.Second) } }
启动