Created
January 23, 2019 19:28
-
-
Save lidizheng/825f1b255767a90fb3a5d4be54071678 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##### server.py start ##### | |
from concurrent import futures | |
import time | |
import logging | |
import grpc | |
import chunker_pb2 | |
import chunker_pb2_grpc | |
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 | |
_CHUNKER_SIZE = 4 | |
_DATA_TO_SEND = 'Hello gRPC Python World!' | |
def _chunk_bytes(data, chunker_size): | |
index = 0 | |
while index < len(data): | |
yield chunker_pb2.Chunk( | |
chunk=data[index:index+chunker_size] | |
) | |
index += chunker_size | |
class Chunker(chunker_pb2_grpc.ChunkerServicer): | |
@staticmethod | |
def Chunker(request, unused_context): | |
return _chunk_bytes( | |
_DATA_TO_SEND, | |
_CHUNKER_SIZE) | |
def serve(): | |
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) | |
chunker_pb2_grpc.add_ChunkerServicer_to_server(Chunker(), server) | |
server.add_insecure_port('[::]:50051') | |
server.start() | |
try: | |
while True: | |
time.sleep(_ONE_DAY_IN_SECONDS) | |
except KeyboardInterrupt: | |
server.stop(0) | |
if __name__ == '__main__': | |
logging.basicConfig() | |
serve() | |
##### server.py end ##### | |
##### client.py start #####from __future__ import print_function | |
import logging | |
from google.protobuf import empty_pb2 | |
import grpc | |
import chunker_pb2 | |
import chunker_pb2_grpc | |
def run(): | |
# NOTE(gRPC Python Team): .close() is possible on a channel and should be | |
# used in circumstances in which the with statement does not fit the needs | |
# of the code. | |
with grpc.insecure_channel('localhost:50051') as channel: | |
stub = chunker_pb2_grpc.ChunkerStub(channel) | |
try: | |
response_iterator = stub.Chunker(empty_pb2.Empty()) | |
received_bytes = bytes() | |
for response in response_iterator: | |
received_bytes += response.chunk | |
print('Received %d bytes...', len(response.chunk)) | |
except grpc.RpcError as rpc_error: | |
print('Handle exception here...') | |
raise rpc_error | |
print('Concatenated Response:') | |
print(received_bytes) | |
if __name__ == '__main__': | |
logging.basicConfig() | |
run() | |
##### client.py end ##### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Program doesn't execute. You need to convert string within
_DATA_TO_SEND
to bytes before chunking aschunker_pb2.Chunk
is expecting bytes not str._DATA_TO_SEND = b'Hello gRPC Python World!'