gpt4 book ai didi

python - 接收流时中断python grpc客户端

转载 作者:行者123 更新时间:2023-11-30 22:22:02 26 4
gpt4 key购买 nike

我正在玩一点 gRPC,我不知道如何在接收流时关闭客户端和服务器之间的连接。客户端和服务器端都是用Python编写的。

例如,我的服务器从队列中读取消息并生成每条消息。我的想法是客户端订阅服务器并开始接收这些消息。

我的问题是:

  • 我希望在按下 CTRL+C 时杀死客户端,但它会卡在当前代码中。怎样才能正确完成呢?
  • 服务器如何意识到客户端已停止监听?

我的 nbi.proto 文件:

syntax = "proto3";
service Messenger {
rpc subscribe(Null) return (stream Message) {}
}

message Null {}

message Message {
string value = 1;
}

Python 客户端:

import test_pb2_grpc as test_grpc
import test_pb2 as test
import grpc

def run():
channel = grpc.insecure_channel('localhost:50051')
stub = test_grpc.MessengerStub(channel)

stream = stub.subscribe(test.Null())
try:
for e in stream:
print e
except grpc._channel._Rendezvous as err:
print err
except KeyboardInterrupt:
stub.unsuscribe(test.Null)

Python 服务器:

import test_pb2_grpc as test_grpc
import test_pb2 as test
from Queue import Empty
import grpc

class Messenger(test_grpc.MessengerServicer):
def __init__(self, queue):
self.queue = queue

def subscribe(self, request, context):
while True:
try:
yield self.queue.get(block=True, timeout=0.1)
except Empty:
continue
except Exception as e:
logger.error(e)
break
return

最佳答案

I would like to get the client killed whenever CTRL+C is pressed, but it gets stuck with the current code. How can it be done properly?

KeyboardInterrupt 应足以终止客户端应用程序。该进程可能卡在 stub.unsubscribe 上。如果您使用客户端断开连接回调,也许您不需要显式取消订阅。

How does the server realize that the client has stopped listening?

您可以add a callback to the context object它被传递到您的 Messenger.subscribe 方法。客户端断开连接时调用回调。

顺便说一句,您可以使用empty.proto查看代替您的 Null 类型。

关于python - 接收流时中断python grpc客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48448577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com