1/* 2 * 3 * Copyright 2019 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 19// Binary server is an example server. 20package main 21 22import ( 23 "context" 24 "flag" 25 "fmt" 26 "log" 27 "net" 28 "time" 29 30 "google.golang.org/grpc" 31 "google.golang.org/grpc/keepalive" 32 33 pb "google.golang.org/grpc/examples/features/proto/echo" 34) 35 36var port = flag.Int("port", 50052, "port number") 37 38var kaep = keepalive.EnforcementPolicy{ 39 MinTime: 5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection 40 PermitWithoutStream: true, // Allow pings even when there are no active streams 41} 42 43var kasp = keepalive.ServerParameters{ 44 MaxConnectionIdle: 15 * time.Second, // If a client is idle for 15 seconds, send a GOAWAY 45 MaxConnectionAge: 30 * time.Second, // If any connection is alive for more than 30 seconds, send a GOAWAY 46 MaxConnectionAgeGrace: 5 * time.Second, // Allow 5 seconds for pending RPCs to complete before forcibly closing connections 47 Time: 5 * time.Second, // Ping the client if it is idle for 5 seconds to ensure the connection is still active 48 Timeout: 1 * time.Second, // Wait 1 second for the ping ack before assuming the connection is dead 49} 50 51// server implements EchoServer. 52type server struct { 53 pb.UnimplementedEchoServer 54} 55 56func (s *server) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { 57 return &pb.EchoResponse{Message: req.Message}, nil 58} 59 60func main() { 61 flag.Parse() 62 63 address := fmt.Sprintf(":%v", *port) 64 lis, err := net.Listen("tcp", address) 65 if err != nil { 66 log.Fatalf("failed to listen: %v", err) 67 } 68 69 s := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp)) 70 pb.RegisterEchoServer(s, &server{}) 71 72 if err := s.Serve(lis); err != nil { 73 log.Fatalf("failed to serve: %v", err) 74 } 75} 76