main.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. "flag"
  23. "fmt"
  24. "io"
  25. "log"
  26. "math/rand"
  27. "net"
  28. "time"
  29. "google.golang.org/grpc"
  30. "google.golang.org/grpc/codes"
  31. pb "google.golang.org/grpc/examples/features/proto/echo"
  32. "google.golang.org/grpc/metadata"
  33. "google.golang.org/grpc/status"
  34. )
  35. var port = flag.Int("port", 50051, "the port to serve on")
  36. const (
  37. timestampFormat = time.StampNano
  38. streamingCount = 10
  39. )
  40. type server struct{}
  41. func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) {
  42. fmt.Printf("--- UnaryEcho ---\n")
  43. // Create trailer in defer to record function return time.
  44. defer func() {
  45. trailer := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
  46. grpc.SetTrailer(ctx, trailer)
  47. }()
  48. // Read metadata from client.
  49. md, ok := metadata.FromIncomingContext(ctx)
  50. if !ok {
  51. return nil, status.Errorf(codes.DataLoss, "UnaryEcho: failed to get metadata")
  52. }
  53. if t, ok := md["timestamp"]; ok {
  54. fmt.Printf("timestamp from metadata:\n")
  55. for i, e := range t {
  56. fmt.Printf(" %d. %s\n", i, e)
  57. }
  58. }
  59. // Create and send header.
  60. header := metadata.New(map[string]string{"location": "MTV", "timestamp": time.Now().Format(timestampFormat)})
  61. grpc.SendHeader(ctx, header)
  62. fmt.Printf("request received: %v, sending echo\n", in)
  63. return &pb.EchoResponse{Message: in.Message}, nil
  64. }
  65. func (s *server) ServerStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error {
  66. fmt.Printf("--- ServerStreamingEcho ---\n")
  67. // Create trailer in defer to record function return time.
  68. defer func() {
  69. trailer := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
  70. stream.SetTrailer(trailer)
  71. }()
  72. // Read metadata from client.
  73. md, ok := metadata.FromIncomingContext(stream.Context())
  74. if !ok {
  75. return status.Errorf(codes.DataLoss, "ServerStreamingEcho: failed to get metadata")
  76. }
  77. if t, ok := md["timestamp"]; ok {
  78. fmt.Printf("timestamp from metadata:\n")
  79. for i, e := range t {
  80. fmt.Printf(" %d. %s\n", i, e)
  81. }
  82. }
  83. // Create and send header.
  84. header := metadata.New(map[string]string{"location": "MTV", "timestamp": time.Now().Format(timestampFormat)})
  85. stream.SendHeader(header)
  86. fmt.Printf("request received: %v\n", in)
  87. // Read requests and send responses.
  88. for i := 0; i < streamingCount; i++ {
  89. fmt.Printf("echo message %v\n", in.Message)
  90. err := stream.Send(&pb.EchoResponse{Message: in.Message})
  91. if err != nil {
  92. return err
  93. }
  94. }
  95. return nil
  96. }
  97. func (s *server) ClientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error {
  98. fmt.Printf("--- ClientStreamingEcho ---\n")
  99. // Create trailer in defer to record function return time.
  100. defer func() {
  101. trailer := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
  102. stream.SetTrailer(trailer)
  103. }()
  104. // Read metadata from client.
  105. md, ok := metadata.FromIncomingContext(stream.Context())
  106. if !ok {
  107. return status.Errorf(codes.DataLoss, "ClientStreamingEcho: failed to get metadata")
  108. }
  109. if t, ok := md["timestamp"]; ok {
  110. fmt.Printf("timestamp from metadata:\n")
  111. for i, e := range t {
  112. fmt.Printf(" %d. %s\n", i, e)
  113. }
  114. }
  115. // Create and send header.
  116. header := metadata.New(map[string]string{"location": "MTV", "timestamp": time.Now().Format(timestampFormat)})
  117. stream.SendHeader(header)
  118. // Read requests and send responses.
  119. var message string
  120. for {
  121. in, err := stream.Recv()
  122. if err == io.EOF {
  123. fmt.Printf("echo last received message\n")
  124. return stream.SendAndClose(&pb.EchoResponse{Message: message})
  125. }
  126. message = in.Message
  127. fmt.Printf("request received: %v, building echo\n", in)
  128. if err != nil {
  129. return err
  130. }
  131. }
  132. }
  133. func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
  134. fmt.Printf("--- BidirectionalStreamingEcho ---\n")
  135. // Create trailer in defer to record function return time.
  136. defer func() {
  137. trailer := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
  138. stream.SetTrailer(trailer)
  139. }()
  140. // Read metadata from client.
  141. md, ok := metadata.FromIncomingContext(stream.Context())
  142. if !ok {
  143. return status.Errorf(codes.DataLoss, "BidirectionalStreamingEcho: failed to get metadata")
  144. }
  145. if t, ok := md["timestamp"]; ok {
  146. fmt.Printf("timestamp from metadata:\n")
  147. for i, e := range t {
  148. fmt.Printf(" %d. %s\n", i, e)
  149. }
  150. }
  151. // Create and send header.
  152. header := metadata.New(map[string]string{"location": "MTV", "timestamp": time.Now().Format(timestampFormat)})
  153. stream.SendHeader(header)
  154. // Read requests and send responses.
  155. for {
  156. in, err := stream.Recv()
  157. if err == io.EOF {
  158. return nil
  159. }
  160. if err != nil {
  161. return err
  162. }
  163. fmt.Printf("request received %v, sending echo\n", in)
  164. if err := stream.Send(&pb.EchoResponse{Message: in.Message}); err != nil {
  165. return err
  166. }
  167. }
  168. }
  169. func main() {
  170. flag.Parse()
  171. rand.Seed(time.Now().UnixNano())
  172. lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
  173. if err != nil {
  174. log.Fatalf("failed to listen: %v", err)
  175. }
  176. fmt.Printf("server listening at %v\n", lis.Addr())
  177. s := grpc.NewServer()
  178. pb.RegisterEchoServer(s, &server{})
  179. s.Serve(lis)
  180. }