douxia3505
2018-03-20 19:59
浏览 88
已采纳

试图了解Golang中gRPC客户端中通道的使用

Could someone please help me understand the usage of the channel in the client side of gRPC code here (for bidirectional streaming RPC): https://grpc.io/docs/tutorials/basic/go.html

This is the code:

stream, err := client.RouteChat(context.Background())
waitc := make(chan struct{})
go func() {
    for {
        in, err := stream.Recv()
        if err == io.EOF {
            // read done.
            close(waitc)
            return
        }
        if err != nil {
            log.Fatalf("Failed to receive a note : %v", err)
        }
        log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude)
    }
}()
for _, note := range notes {
    if err := stream.Send(note); err != nil {
        log.Fatalf("Failed to send a note: %v", err)
    }
}
stream.CloseSend()
<-waitc

Thanks!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanbanfei2875 2018-03-20 20:17
    已采纳

    Channel waitc used to make main thread wait for goroutine to finish receiving from server and gracefully shutdown connection.

    <-waitc // is a blocking operation. It can evaluate when channel been closed
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题