1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| > vim hello-world/cmd/server.go
package main
import ( pb "app/protos" "context" "fmt" "log" "net"
"google.golang.org/grpc" "google.golang.org/grpc/reflection" )
const ( port = ":50051" )
type server struct { pb.UnimplementedHelloWorldServer }
func (s *server) Send(ctx context.Context, request *pb.SendRequest) (*pb.SendResponse, error) { fmt.Println("client send msg: ", request.Msg) return &pb.SendResponse{ Code: 0, Msg: "success", Data: []*pb.SendRequest{ &pb.SendRequest{ Msg: request.Msg + " response", }, }, }, nil }
func (s *server) Count(ctx context.Context, request *pb.CountRequest) (*pb.CountResponse, error) { fmt.Println("client count A:", request.A, " client count B: ", request.B) return &pb.CountResponse{ Code: 0, Msg: "success", Sum: request.A + request.B, },nil }
func main() { listen, err := net.Listen("tcp", port) if err != nil { log.Fatalf("listener error: $v", err) }
s := grpc.NewServer() pb.RegisterHelloWorldServer(s, &server{})
reflection.Register(s)
if err := s.Serve(listen); err != nil { log.Fatalf("failed to serve: %v", err) } }
|