有没有一种方法可以在连接的套接字net.conn上构建一个gRPC服务器?

huangapple go评论78阅读模式
英文:

Is there a way to construct a grpc server on a connected socket net.conn?

问题

在Go语言中的典型用法是:

server := grpc.NewServer()

pb.RegisterUserServer(server, &userSrvc.UserServer{})

addr := ":" + env.GetMyRpcPort()

lis, _ := net.Listen("tcp", addr)

server.Serve(lis)

我想知道是否可以在已连接的conn上运行服务器,像这样:

conn, _ := net.Dial("tcp", ":8080")
server.Serve(conn)

客户端首先连接到服务器,然后在已连接的net.conn上构建一个gRPC服务器,然后服务器可以通过RPC调用客户端,向客户端推送一些消息作为请求。

英文:

The typical usage in go is:

	server := grpc.NewServer()
	
	pb.RegisterUserServer(server, &userSrvc.UserServer{})

	addr := ":" + env.GetMyRpcPort()

	lis, _ := net.Listen("tcp", addr)

	server.Serve(lis)

I wonder can I run a server on a connected conn like:

conn, _ := net.Dial("tcp",":8080")
server.Serve(conn)

The client connect to the server first, and then construct a grpc server on the connected net.conn, then the server can rpc call the client to push some message as a request to the client.

答案1

得分: 2

我认为你需要一个双向流式传输
这里有一个使用Go语言实现双向GRPC的详细示例:https://github.com/pahanini/go-grpc-bidirectional-streaming-example。

conn, err := grpc.Dial(":50005", grpc.WithInsecure())
...
client := pb.NewMathClient(conn)
stream, err := client.Max(context.Background())
...
req := pb.Request{Num: rnd}
err := stream.Send(&req)
英文:

I think that you need a bidirectional streaming.
Here is one elaborated example of using bidirectional GRPC in Go: https://github.com/pahanini/go-grpc-bidirectional-streaming-example.

conn, err := grpc.Dial(":50005", grpc.WithInsecure())
...
client := pb.NewMathClient(conn)
stream, err := client.Max(context.Background())
...
req := pb.Request{Num: rnd}
err := stream.Send(&req)

huangapple
  • 本文由 发表于 2022年1月4日 18:18:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/70577194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定