server.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # Copyright 2019 gRPC authors.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """The example of four ways of data transmission using gRPC in Python."""
  15. from concurrent import futures
  16. from threading import Thread
  17. import grpc
  18. import demo_pb2
  19. import demo_pb2_grpc
  20. __all__ = 'DemoServer'
  21. SERVER_ADDRESS = 'localhost:23333'
  22. SERVER_ID = 1
  23. class DemoServer(demo_pb2_grpc.GRPCDemoServicer):
  24. # 一元模式(在一次调用中, 客户端只能向服务器传输一次请求数据, 服务器也只能返回一次响应)
  25. # unary-unary(In a single call, the client can only send request once, and the server can
  26. # only respond once.)
  27. def SimpleMethod(self, request, context):
  28. print("SimpleMethod called by client(%d) the message: %s" %
  29. (request.client_id, request.request_data))
  30. response = demo_pb2.Response(
  31. server_id=SERVER_ID,
  32. response_data="Python server SimpleMethod Ok!!!!")
  33. return response
  34. # 客户端流模式(在一次调用中, 客户端可以多次向服务器传输数据, 但是服务器只能返回一次响应)
  35. # stream-unary (In a single call, the client can transfer data to the server several times,
  36. # but the server can only return a response once.)
  37. def ClientStreamingMethod(self, request_iterator, context):
  38. print("ClientStreamingMethod called by client...")
  39. for request in request_iterator:
  40. print("recv from client(%d), message= %s" %
  41. (request.client_id, request.request_data))
  42. response = demo_pb2.Response(
  43. server_id=SERVER_ID,
  44. response_data="Python server ClientStreamingMethod ok")
  45. return response
  46. # 服务端流模式(在一次调用中, 客户端只能一次向服务器传输数据, 但是服务器可以多次返回响应)
  47. # unary-stream (In a single call, the client can only transmit data to the server at one time,
  48. # but the server can return the response many times.)
  49. def ServerStreamingMethod(self, request, context):
  50. print("ServerStreamingMethod called by client(%d), message= %s" %
  51. (request.client_id, request.request_data))
  52. # 创建一个生成器
  53. # create a generator
  54. def response_messages():
  55. for i in range(5):
  56. response = demo_pb2.Response(
  57. server_id=SERVER_ID,
  58. response_data=("send by Python server, message=%d" % i))
  59. yield response
  60. return response_messages()
  61. # 双向流模式 (在一次调用中, 客户端和服务器都可以向对方多次收发数据)
  62. # stream-stream (In a single call, both client and server can send and receive data
  63. # to each other multiple times.)
  64. def BidirectionalStreamingMethod(self, request_iterator, context):
  65. print("BidirectionalStreamingMethod called by client...")
  66. # 开启一个子线程去接收数据
  67. # Open a sub thread to receive data
  68. def parse_request():
  69. for request in request_iterator:
  70. print("recv from client(%d), message= %s" %
  71. (request.client_id, request.request_data))
  72. t = Thread(target=parse_request)
  73. t.start()
  74. for i in range(5):
  75. yield demo_pb2.Response(
  76. server_id=SERVER_ID,
  77. response_data=("send by Python server, message= %d" % i))
  78. t.join()
  79. def main():
  80. server = grpc.server(futures.ThreadPoolExecutor())
  81. demo_pb2_grpc.add_GRPCDemoServicer_to_server(DemoServer(), server)
  82. server.add_insecure_port(SERVER_ADDRESS)
  83. print("------------------start Python GRPC server")
  84. server.start()
  85. server.wait_for_termination()
  86. # If raise Error:
  87. # AttributeError: '_Server' object has no attribute 'wait_for_termination'
  88. # You can use the following code instead:
  89. # import time
  90. # while 1:
  91. # time.sleep(10)
  92. if __name__ == '__main__':
  93. main()