baidu-brpc学习之文件传输实例编写

file.proto

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

syntax="proto2";
package example;

option cc_generic_services = true;

//=====service 1
message EchoRequest {
	required string message = 1;
};

message EchoResponse {
	required string message = 1;
};

service EchoService {
	rpc Echo(EchoRequest) returns (EchoResponse);
};


//=====service 2
service Greeter {
	// Sends a greeting
	rpc SayHello (HelloRequest) returns (HelloReply) {}
};

// The request message containing the user's name.
message HelloRequest {
	required string name = 1;
};

// The response message containing the greetings
message HelloReply {
	required string message = 1;
};

//=====service 3
message FileUpLoadRequest {
	required string name = 1;
	repeated bytes samples = 2;
}

message FileUpLoadResponse {
	required int32 Error = 1;
}
service FileUp {
	rpc UpLoadFile(FileUpLoadRequest) returns (FileUpLoadRequest) {}
}

clien.cpp

#include <cstdio>
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <brpc/channel.h>

#include <fcntl.h>
#include <unistd.h>

#include "file.pb.h"


DEFINE_string(attachment, "", "Carry this along with requests");
DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in src/brpc/options.proto");
DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(server, "127.0.0.1:8000", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 20000, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)");
DEFINE_int32(interval_ms, 3000, "Milliseconds between consecutive requests");


/* argv[2]:-u 上传 argv[2]: 本地上传文件名,argv[3]远端落地文件名*/
/* argv[2]:-d 下载 argv[2]: 本地落地文件名,argv[3]远端下载文件名*/

int main(int argc, char* argv[]) 
{

	if (argc < 4) {

		LOG(ERROR) << "The command lines is error";
		return 0;
	}

	brpc::Channel channel;

	// Initialize the channel, NULL means using default options.
	brpc::ChannelOptions options;
	options.protocol = FLAGS_protocol;
	options.connection_type = FLAGS_connection_type;
	options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
	options.max_retry = FLAGS_max_retry;

	if (channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) {

		LOG(ERROR) << "Fail to initialize channel";
		return -1;
	}

	example::FileUp_Stub fileup_stub(&channel);
	//example::FileDownLoad_Stub filedownload_stub(&channel);
	int log_id = 0;

	while (!brpc::IsAskedToQuit()) 
	{
		brpc::Controller cntl;

		if (strcmp(argv[1], "-u") == 0) {

			int filefd = -1;
			int bytes_read = 0;
			char chunck[2048];

			if ((filefd = open(argv[2], O_RDWR)) < 0) {

				LOG(ERROR) << "The upload file opration is failure!";
				return 0;
			}

			do
			{
				cntl.Reset();
				example::FileUpLoadRequest fileRequest;
				example::FileUpLoadResponse fileReply;

				memset(chunck, 0, sizeof(chunck));
				if ((bytes_read = read(filefd, chunck, sizeof(chunck))) < 0) {

					LOG(ERROR) << "The upload file read is failure!";
					break;
				}

				if (bytes_read == 0) {

					LOG(INFO) << "The upload file is completed!";
					break;
				}

				fileRequest.set_name(argv[3]);
				fileRequest.set_chuncks(chunck, bytes_read);

				cntl.set_log_id(log_id++);
				fileup_stub.UpLoadFile(&cntl, &fileRequest, &fileReply, NULL);

				if (fileReply.length() < 0) {

					LOG(ERROR) << "The upload file remote is failure!";
					break;
				}

			} while (true);

			close(filefd);
			return 0;
		}
		else if(strcmp(argv[3], "-p") == 0){
			
			return 0;
		}
		else {

			printf("The operation is failure!\n");
			return 0;
		}

		usleep(FLAGS_interval_ms * 10L);
	}

	LOG(INFO) << "EchoClient is going to quit";
	return 0;
}

server.cpp

#include <cstdio>
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <brpc/server.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

#include "file.pb.h"

DEFINE_int32(port, 8000, "TCP Port of this server");
DEFINE_int32(idle_timeout_s, -1, "Connection will be closed if there is no ""read/write operations during the last `idle_timeout_s'");

//文件创建访问权限
#define RWRWRW (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)

namespace example {

	class FileUpImpl : public FileUp {
	public:
		FileUpImpl() {};
		virtual ~FileUpImpl() {};

		void UpLoadFile(google::protobuf::RpcController* cntl_base,
			const FileUpLoadRequest* req,
			FileUpLoadResponse* res,
			google::protobuf::Closure* done) {

			int bytes = -1;
			int filefd = -1;

			brpc::ClosureGuard done_guard(done);
			brpc::Controller* cntl =
				static_cast<brpc::Controller*>(cntl_base);

			std::string filename = req->name();
			std::string chunck = req->chuncks();

			printf("%s\n", filename.c_str());

			if ((filefd = open(filename.c_str(), O_RDWR | O_CREAT | O_APPEND, RWRWRW)) < 0) {

				LOG(ERROR) << "The called open is failure!";
			}

			if ((bytes = write(filefd, chunck.data(), (size_t)chunck.size())) < 0) {

				LOG(ERROR) << "The called write is failure!";
			}

			res->set_length(bytes);
			close(filefd);

			usleep(10);
		}
	};
}  // namespace example


int main(int argc, char* argv[]) 
{
	brpc::Server server;
	example::FileUpImpl fileup_impl;

	if (server.AddService(&fileup_impl,
		brpc::SERVER_DOESNT_OWN_SERVICE) != 0) {

		LOG(ERROR) << "Fail to add service";
		return -1;
	}

	// Start the server.
	brpc::ServerOptions options;
	options.idle_timeout_sec = FLAGS_idle_timeout_s;
	if (server.Start(FLAGS_port, &options) != 0) {

		LOG(ERROR) << "Fail to start EchoServer";
		return -1;
	}

	server.RunUntilAskedToQuit();
	return 0;
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值