簡體   English   中英

在 python 服務器和 android(java) 客戶端之間使用 grpc 創建連接

[英]Creating a connection using grpc between a python server and an android(java) client

我在本地機器上的 python 上運行一個簡單的 GRPC 服務器。 當我嘗試使用 java 從我的 android 設備連接到它時,我不斷收到Caused by: io.grpc.StatusRuntimeException: UNAVAILABLE錯誤: 請注意,我嘗試通過 python 客戶端連接到服務器,並且它按預期工作。 該問題僅在使用 java 客戶端時存在。

我嘗試使用 python 中的客戶端來檢查 proto 文件是否存在問題,並且它工作正常,所以我認為問題在於python服務器和java客戶端組合之間的連接。

    private ManagedChannel mChannel;
    private TestGrpc.TestBlockingStub blockingStub;
    private TestGrpc.TestStub asyncStub;

    mChannel = ManagedChannelBuilder.forAddress("10.0.0.17", 50051).build();
    blockingStub = TestGrpc.newBlockingStub(mChannel);
    helloMessage testMessage = helloMessage.newBuilder()
    .setMessageContent("NAME")
    .build();
    helloMessage msg= blockingStub.sayHello(testMessage);

原型文件:

syntax="proto3";
option java_package = "io.grpc.testing";
option java_multiple_files = true;
option java_outer_classname = "TestClass";
option objc_class_prefix = "TST ";

package TestCode;

service Test{
    rpc sayHello(helloMessage) returns (helloMessage) {}
    rpc streamTest(helloMessage) returns (stream helloMessage) {}
}

message helloMessage{
    string messageContent = 1;
}

python 服務器

import protofile_pb2
import protofile_pb2_grpc


# create a class to define the server functions, derived from
# calculator_pb2_grpc.CalculatorServicer
class TestService(protofile_pb2_grpc.TestServicer):

    # calculator.square_root is exposed here
    # the request and response are of the data type
    # calculator_pb2.Number
    def sayHello(self, request, context):
        response = protofile_pb2.helloMessage()
        response.messageContent = "hello mister "+request.messageContent
        return response
# create a gRPC server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

# use the generated function `add_CalculatorServicer_to_server`
# to add the defined class to the server
protofile_pb2_grpc.add_TestServicer_to_server(
        TestService(), server)

# listen on port 50051
print('Starting server. Listening on port 50051.')
server.add_insecure_port('[::]:50051')
server.start()

# since server.start() will not block,
# a sleep-loop is added to keep alive
try:
    while True:
        time.sleep(86400)
except KeyboardInterrupt:
    server.stop(0)

這應該返回一個具有一個值的迭代器,即字符串:“hello miser NAME”。 實際結果: Caused by:io.grpc.StatusRuntimeException: UNAVAILABLE

我發現這個問題的解決方案是我使用了一個不安全的端口進行通信,並使用 SSL 進行來自 android 的連接,該連接預期握手。 您可以通過創建服務器證書並使用安全通道通信或將更改更改為 build with.Plaintext() 來解決此問題

https://grpc.io/docs/guides/auth/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM