一、通过socket将grpc接收的数据传输到django中
# django+grpc+socket(服务端给客户端发送文件) 配置过程# 将socket的服务端作为一个线程,放在grpc服务端下,一起启动# 将socket的客户端作为一个模块,直接嵌入在websocket的while True循环之下接收数据并传输到页面端
二、直接融合
django+grpc配置过程# 首先利用data.proto生成两个文件,放在python安装目录包下(即Lib--》site-packet下)# 将grpc的服务端作为一个线程,方法websocket下。如下:
# class ServerGreeter(data_pb2_grpc.dataServicer): # def serving(self, request, context): # print('serving...',datetime.datetime.fromtimestamp(time.time())) # # logging.info('serving...') # data_64 = base64.b64decode(request.cmd) # data_str=data_64.decode() # q.put(data_str) # return data_pb2.data_reply(values="ok") # # def grpc_connect(): # server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) # # 在服务器中添加派生的接口服务(自己实现了处理函数) # data_pb2_grpc.add_dataServicer_to_server(ServerGreeter(), server) # # 添加监听端口 # myname = socket.gethostname() # myip = socket.gethostbyname(myname) # server.add_insecure_port('127.0.0.1' + ':' + '9001') # print('myip:', myip) # # 存储数据线程 # # t = threading.Thread(target=data_manage, args=()) # # t.start() # # # 发送数据给web前端线程 # # t1 = threading.Thread(target=send_data, args=()) # # t1.start() # server.start() # try: # while True: # time.sleep(60 * 60 * 24) # except KeyboardInterrupt: # server.stop(0) # @accept_websocket # def echo(request): # if not request.is_websocket():#判断是不是websocket连接 # try:#如果是普通的http方法 # message = request.GET['message'] # return HttpResponse(message) # except: # return render(request,'index.html') # else: # for message in request.websocket: # t = threading.Thread(target=grpc_connect, args=()) # t.start()
调试经验:
# 一般不关闭socket # 遇到异常不处理可用pass # 定位到While True:进行调试 # 启动客户端,调试服务端 # 启动服务端,调试客户端