|
27 | 27 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
28 | 28 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
29 | 29 |
|
30 | | -"""The Python implementation of the GRPC helloworld.Greeter client.""" |
| 30 | +"""The Python implementation of the GRPC helloworld.Greeter server.""" |
31 | 31 |
|
32 | 32 | from __future__ import print_function |
33 | 33 |
|
34 | 34 | import grpc |
| 35 | +import time |
35 | 36 |
|
36 | | -import helloworld_pb2 |
| 37 | +from concurrent import futures |
| 38 | +from examples.helloworld.proto import helloworld_pb2 |
37 | 39 |
|
| 40 | +_ONE_DAY_IN_SECONDS = 60 * 60 * 24 |
38 | 41 |
|
39 | | -def run(): |
40 | | - channel = grpc.insecure_channel('localhost:50051') |
41 | | - stub = helloworld_pb2.GreeterStub(channel) |
42 | | - response = stub.SayHello(helloworld_pb2.HelloRequest(name='you')) |
43 | | - print("Greeter client received: " + response.message) |
44 | 42 |
|
| 43 | +class _GreeterServer(object): |
| 44 | + |
| 45 | + def __init__(self, greeter_service, server_port): |
| 46 | + self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) |
| 47 | + helloworld_pb2.add_GreeterServicer_to_server(greeter_service, self.server) |
| 48 | + self.server.add_insecure_port('[::]:{server_port}'.format(server_port=server_port)) |
| 49 | + |
| 50 | + def start(self): |
| 51 | + self.server.start() |
| 52 | + |
| 53 | + def stop(self): |
| 54 | + self.server.stop(0) |
| 55 | + |
| 56 | + def await_termination(self): |
| 57 | + """ |
| 58 | + server.start() doesn't block so we explicitly block here unless someone keyboard-exits us. |
| 59 | + :return: |
| 60 | + """ |
| 61 | + try: |
| 62 | + while True: |
| 63 | + time.sleep(_ONE_DAY_IN_SECONDS) |
| 64 | + except KeyboardInterrupt: |
| 65 | + self.server.stop(0) |
| 66 | + pass |
| 67 | + |
| 68 | + |
| 69 | +class _GreeterService(helloworld_pb2.GreeterServicer): |
| 70 | + |
| 71 | + def SayHello(self, hello_request, context): |
| 72 | + print("Greeter server received: " + hello_request.name) |
| 73 | + hello_reply = helloworld_pb2.HelloReply() |
| 74 | + hello_reply.message = 'Hello {name}'.format(name=hello_request.name) |
| 75 | + return hello_reply |
| 76 | + |
| 77 | + |
| 78 | +def main(): |
| 79 | + greeter_server = _GreeterServer(_GreeterService(), 50051) |
| 80 | + greeter_server.start() |
| 81 | + greeter_server.await_termination() |
45 | 82 |
|
46 | 83 | if __name__ == '__main__': |
47 | | - run() |
| 84 | + main() |
0 commit comments