默认情况下,grpc服务端和客户端的收发消息大小都是4M,可以通过自己修改该大小。由于设置的函数参数是int的,所以最大的能使用的消息大小也是2G。如果超过2G的数据可以使用stream的方式。 grpc默认接受数据大小为4MB,如果发送的数据超过该值,需要进行修改。未经设置的默认值如下设置:
1 2 3 4 #define GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH (-1) #define GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH (4 * 1024 * 1024)
服务端调整消息大小 1 2 3 4 5 6 7 8 9 10 int kMaxMessageSize = INT_MAX;grpc::ServerBuilder builder; builder.SetMaxReceiveMessageSize (kMaxMessageSize); builder.SetMaxSendMessageSize (kMaxMessageSize); builder.AddListeningPort ("0.0.0.0:8081" , grpc::InsecureServerCredentials ()); builder.RegisterService (&mMyService); std::unique_ptr<grpc::Server> server (builder.BuildAndStart()) ;server->Wait ();
客户端调整消息大小 1 2 3 4 5 grpc::ChannelArguments cArgs; cArgs.SetInt (GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, INT_MAX); std::shared_ptr<grpc::Channel> channel = grpc::CreateCustomChannel ("localhost:8081" , grpc::InsecureChannelCredentials (), cArgs); std::unique_ptr<arc::MyService::Stub> stub (arc::MyService::NewStub(channel)) ;
grpc stream传输大文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 request.clear_data (); auto image = request.mutable_image ();int64_t size = 1024 * 1024 * 10 ;char * buf = new char [size];std::ifstream file (path, std::ios::in | std::ios::binary) ;if (!file.is_open ()) { return ; } while (!file.eof ()) { std::streamsize len = file.read (buf, size).gcount (); image->set_image_content (buf, len); writer->Write (request); } writer->Write (request); delete buf;writer->WritesDone (); grpc::Status status = writer->Finish ();
message与json字符串的转换 1 2 3 4 5 6 7 8 9 google::protobuf::util::JsonOptions opt; opt.add_whitespace = true ; opt.always_print_primitive_fields = true ; opt.preserve_proto_field_names = true ; std::string str; google::protobuf::util::MessageToJsonString (msg, &str, opt); google::protobuf::util::JsonStringToMessage (StringPiece input, Message *message);