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

时间:2018-03-20 19:59:20

标签: go grpc

有人可以帮我理解gRPC代码客户端中频道的使用情况(对于双向流RPC): https://grpc.io/docs/tutorials/basic/go.html

这是代码:

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

谢谢!

1 个答案:

答案 0 :(得分:2)

用于使waitc线程的频道main等待goroutine完成从服务器接收并正常关闭连接。

<-waitc // is a blocking operation. It can evaluate when channel been closed
相关问题