Skip to content

Commit

Permalink
grpc streaming
Browse files Browse the repository at this point in the history
  • Loading branch information
Rahugg committed Oct 31, 2023
1 parent a64b2b1 commit f2004b4
Show file tree
Hide file tree
Showing 5 changed files with 506 additions and 21 deletions.
26 changes: 26 additions & 0 deletions gRPC_client/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,30 @@ func main() {
log.Fatalf("error: %s", err)
}
fmt.Println(resp)

ctx, cancel = context.WithTimeout(context.Background(), time.Second)
defer cancel()
stream, err := c.Location(ctx)
if err != nil {
log.Fatalf("error: %s", err)
}

lreq := pb.LocationRequest{
DriverId: "007",
Location: &pb.Location{
Lat: 51.4871871,
Lng: -0.1266743,
},
}
for i := 0.000; i < 0.003; i += 0.001 {
lreq.Location.Lat += i
if err = stream.Send(&lreq); err != nil {
log.Fatalf("error: %s", err)
}
}
lresp, err := stream.CloseAndRecv()
if err != nil {
log.Fatalf("error: %s", err)
}
fmt.Println(lresp)
}
27 changes: 27 additions & 0 deletions gRPC_server/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package main

import (
"context"
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
"io"
"log"
"net"

Expand Down Expand Up @@ -48,6 +50,31 @@ func (r *Rides) Start(ctx context.Context, req *pb.StartRequest) (*pb.StartRespo
return &resp, nil
}

func (r *Rides) Location(stream pb.Rides_LocationServer) error {
count := int64(0)
driverID := ""
for {
req, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
err = status.Errorf(codes.Internal, "can't read")
if err != nil {
return err
}
}
// TODO: update db
driverID = req.DriverId
count++
}
resp := pb.LocationResponse{
DriverId: driverID,
Count: count,
}
return stream.SendAndClose(&resp)
}

type Rides struct {
pb.UnimplementedRidesServer
}
Loading

0 comments on commit f2004b4

Please sign in to comment.