1 回答

TA貢獻1876條經驗 獲得超6個贊
您可以像這樣指定源端口:
cc, err := grpc.Dial("127.0.0.1:6001", grpc.WithInsecure(),
? ? grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
? ? ? ? dst, err := net.ResolveTCPAddr("tcp", addr)
? ? ? ? if err != nil {
? ? ? ? ? ? return nil, err
? ? ? ? }
? ? ? ? src := &net.TCPAddr{
? ? ? ? ? ? IP:? ?net.ParseIP("127.0.0.1"),
? ? ? ? ? ? Port: 6000,
? ? ? ? }
? ? ? ? return net.DialTCP("tcp", src, dst)
? ? }))
但是,如果您的服務器正在偵聽同一端口,這將導致錯誤:
panic: dial tcp 127.0.0.1:6000->127.0.0.1:6001: bind: address already in use
另一種方法是將地址作為元數據傳遞。在客戶端您執行以下操作:
ctx := context.Background()
ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs("address", "127.0.0.1:6000"))
res, err := grpc_health_v1.NewHealthClient(cc).Check(ctx, &grpc_health_v1.HealthCheckRequest{
? ? Service: "test",
})
在服務器上:
func (s *server) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
? ? if md, ok := metadata.FromIncomingContext(ctx); ok {
? ? ? ? addr := md.Get("address")
? ? ? ? // addr == "127.0.0.1:6000"
? ? }
? ? return &grpc_health_v1.HealthCheckResponse{
? ? ? ? Status: grpc_health_v1.HealthCheckResponse_SERVING,
? ? }, nil
}
第三種方法是使用流式傳輸。
- 1 回答
- 0 關注
- 214 瀏覽
添加回答
舉報