Reputation: 51
I am playing a little bit with gRPC and I do not know how to close a connection between a client and the server when receiving a stream. Both the client and the server are written in Python.
For example, my server reads messages from a Queue and it yields each message. My idea is that the client subscribes to the server and starts receiving those messages.
My questions are:
My nbi.proto file:
syntax = "proto3";
service Messenger {
rpc subscribe(Null) return (stream Message) {}
}
message Null {}
message Message {
string value = 1;
}
Python client:
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 server:
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
Upvotes: 1
Views: 4233
Reputation: 4021
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?
The KeyboardInterrupt
should be enough to terminate the client application. Probably the process is hanging on the stub.unsubscribe
. If you use the client disconnection callback, perhaps you don't need to unsubscribe explicitly.
How does the server realize that the client has stopped listening?
You can add a callback to the context object that gets passed to your Messenger.subscribe
method. The callback is called on client disconnection.
By the way, you can look in using empty.proto in place of your Null
type.
Upvotes: 3