main.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Binary server is an example server.
  19. package main
  20. import (
  21. "context"
  22. "fmt"
  23. "log"
  24. "net"
  25. "sync"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/codes"
  28. ecpb "google.golang.org/grpc/examples/features/proto/echo"
  29. "google.golang.org/grpc/status"
  30. )
  31. var (
  32. addrs = []string{":50051", ":50052"}
  33. )
  34. type ecServer struct {
  35. addr string
  36. }
  37. func (s *ecServer) UnaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) {
  38. return &ecpb.EchoResponse{Message: fmt.Sprintf("%s (from %s)", req.Message, s.addr)}, nil
  39. }
  40. func (s *ecServer) ServerStreamingEcho(*ecpb.EchoRequest, ecpb.Echo_ServerStreamingEchoServer) error {
  41. return status.Errorf(codes.Unimplemented, "not implemented")
  42. }
  43. func (s *ecServer) ClientStreamingEcho(ecpb.Echo_ClientStreamingEchoServer) error {
  44. return status.Errorf(codes.Unimplemented, "not implemented")
  45. }
  46. func (s *ecServer) BidirectionalStreamingEcho(ecpb.Echo_BidirectionalStreamingEchoServer) error {
  47. return status.Errorf(codes.Unimplemented, "not implemented")
  48. }
  49. func startServer(addr string) {
  50. lis, err := net.Listen("tcp", addr)
  51. if err != nil {
  52. log.Fatalf("failed to listen: %v", err)
  53. }
  54. s := grpc.NewServer()
  55. ecpb.RegisterEchoServer(s, &ecServer{addr: addr})
  56. log.Printf("serving on %s\n", addr)
  57. if err := s.Serve(lis); err != nil {
  58. log.Fatalf("failed to serve: %v", err)
  59. }
  60. }
  61. func main() {
  62. var wg sync.WaitGroup
  63. for _, addr := range addrs {
  64. wg.Add(1)
  65. go func(addr string) {
  66. defer wg.Done()
  67. startServer(addr)
  68. }(addr)
  69. }
  70. wg.Wait()
  71. }