客户端与服务端互相传输与接收headers
在grpc中headers基于metadata来封装
方法名
在服务端的rpc函数下的方法
context.set_trailing_metadata() 设置header参数,参数只能是元组context.invocation_metadata() 获取RPC调用端(客户端)发出的元组数据对象client.自定义的rpc函数名.with_call() 获取服务端的header,- context.set_compression(grpc.Compression.Gzip) # 以Gzip方式压缩 (grpc会自动解压)
with_call的参数说明
metadata 设置反回header参数,参数只能是元组timeout 设置超时compression 自定义压缩方式
with_call反回参数的方法 trailing_metadata() 客户端获取服务端反回的header参数
options 服务端设置传输大小的参数 具体使用方式看完整代码
完整代码:
单程非流形式的完整代码: helloworld.proto :
syntax = "proto3";
package test;
service grpc_test {
rpc
t_client(t_client_requests)
returns(t_client_response){}
}
message t_client_requests{
string data = 1;
}
message t_client_response{
string result = 1;
}
server.py :
import time
import grpc
import helloworld_pb2 as pb2
import helloworld_pb2_grpc as pb2_grpc
from concurrent import futures
class grpc_test(pb2_grpc.grpc_testServicer):
def t_client(self, request, context):
context.set_trailing_metadata((('name', 'qwq'), ("key", "value")))
headers = context.invocation_metadata()
print(headers)
print(headers[1].key, headers[1].value)
result = f'这是服务端发送的内容!'
context.set_compression(grpc.Compression.Gzip)
print(dir(grpc.Compression))
return pb2.t_client_response(result=result)
def run():
grpc_server = grpc.server(
futures.ThreadPoolExecutor(max_workers=4),
compression=grpc.Compression.Gzip,
options=[
('grpc.max_send_message_length', 50*1024*1024),
('grpc.max_receive_message_length', 50*1024*1024)
],
)
pb2_grpc.add_grpc_testServicer_to_server(grpc_test(), grpc_server)
grpc_server.add_insecure_port('0.0.0.0:50010')
print('server will start at 0.0.0.0:50010')
grpc_server.start()
try:
while 1:
time.sleep(3600)
except Exception as e:
grpc_server.stop(0)
print(e)
if __name__ == '__main__':
run()
client.py :
import json
import random
import time
import grpc
import helloworld_pb2 as pb2
import helloworld_pb2_grpc as pb2_grpc
def run():
conn = grpc.insecure_channel('127.0.0.1:50010')
client = pb2_grpc.grpc_testStub(channel=conn)
str_random = str(random.random())
response, call = client.t_client.with_call(
pb2.t_client_requests(data=str_random),
compression=grpc.Compression.Gzip,
metadata=((('client_key',"clinet_value"),)),
timeout=10,
)
print('*************')
print(response.result)
headers = call.trailing_metadata()
print(headers)
print(headers[0].key, headers[0].value)
print(headers[1].key, headers[1].value)
if __name__ == '__main__':
run()
|