// - server.go -
packagemainimport("errors""io""log""net"pb"github.com/butuzov/sandbox/grpc/client-streaming/proto""google.golang.org/grpc""google.golang.org/grpc/reflection""google.golang.org/protobuf/types/known/wrapperspb")const(address="localhost:4772")// gRPC Server
var_pb.CalculatorServer=(*server)(nil)typeserverstruct{pb.UnsafeCalculatorServer}func(s*server)Avg(streampb.Calculator_AvgServer)error{var(sumuint64cntint)for{res,err:=stream.Recv()iferrors.Is(err,io.EOF){returnstream.SendAndClose(&wrapperspb.DoubleValue{Value:float64(sum)/float64(cnt),})}log.Printf("server got: %v",res.GetValue())sum=sum+res.GetValue()cnt++}returnnil}funcmain(){conn,err:=net.Listen("tcp",address)iferr!=nil{log.Fatalf("failed to listen: %v",err)}deferconn.Close()log.Printf("SERVER Runs @ %s \n",conn.Addr().String())s:=grpc.NewServer()pb.RegisterCalculatorServer(s,&server{})reflection.Register(s)log.Fatalf("failed to serve: %v",s.Serve(conn))}
// - client.go -
packagemainimport("context""log""math/rand"pb"github.com/butuzov/sandbox/grpc/client-streaming/proto""google.golang.org/grpc""google.golang.org/protobuf/types/known/wrapperspb")const(address="localhost:4772")funcmain(){conn,err:=grpc.Dial(address,grpc.WithInsecure())iferr!=nil{log.Fatalf("can not connect with server %v",err)}deferconn.Close()var(client=pb.NewCalculatorClient(conn)ctx=context.Background())ifstream,err:=client.Avg(ctx);err!=nil{log.Fatal(err)}else{fori:=uint64(0);i<10;i++{n:=&wrapperspb.UInt64Value{Value:uint64(rand.Int63n(599))}iferr:=stream.Send(n);err!=nil{log.Fatalf("Send: %v",err)}}ifresp,err:=stream.CloseAndRecv();err!=nil{log.Fatalf("client/Error/CloseAndRecv: %v\n",err)}else{log.Printf("client/Result/CloseAndRecv: %v\n",resp.GetValue())}}}