protobuf的使用

8 篇文章 0 订阅

编译protobuf:
下载源码,使用CMake编译。
注意我的项目用的是Qt mingw编译器,所以在CMake选择编译器的时候要选择mingw,而不是msvc。

使用mingw编译出来的库:protobuf.a,然后加上源码中的google/protobuf目录,事实上这里面有很多.proto文件和源文件可以删除了,甚至很多头文件都用不上。网上没见到提到这一点。

网上有的博客说编译动态库比较好,其实并不是。

.pro配置protobuf静态库:

#添加使用mingw编译的protobuf库
INCLUDEPATH += $$PWD/../third-party/protobuf/include
LIBS += -L$$PWD/../third-party/protobuf/lib -lprotobuf

项目不管release和debug版本都可以用prootobuf release库,只不过不能调试protobuf库。

 

Qt与Java Netty prootbuf对接:

使用ArrayOutputStream,CodedOutputStream,ArrayInputStream,CodedInputStream

发送:

void TcpClient::sendMsg(QByteArray msg)
{
	if (m_socket)
	{

		TestMsg tm;
		tm.set_type("hello");

		qDebug() << "tm len: " << tm.ByteSize();
		int len = tm.ByteSize() + 4;
		char *buffer = new char[len];
		memset(buffer, 0, len);
		google::protobuf::io::ArrayOutputStream arrayOut(buffer, len);
		google::protobuf::io::CodedOutputStream codedOut(&arrayOut);
		codedOut.WriteVarint32(tm.ByteSize());
		tm.SerializeToCodedStream(&codedOut);

		m_socket->write(buffer, len);
	}
}

接收:

void TcpClient::readyRead()
{
	if (!m_socket)
	{
		return;
	}

	while (1)
	{
		m_buf.append(m_socket->readAll());

		if (m_buf.size() < 4)
		{
			break;
		}

		TestMsg tm;
		google::protobuf::io::ArrayInputStream array_in(m_buf.constData(), m_buf.size());
		google::protobuf::io::CodedInputStream coded_in(&array_in);
		google::protobuf::uint32 size;
		coded_in.ReadVarint32(&size);
		google::protobuf::io::CodedInputStream::Limit msg_limit = coded_in.PushLimit(size);
		tm.ParseFromCodedStream(&coded_in);
		coded_in.PopLimit(msg_limit);

		qDebug() << "type size: " << tm.type().size();
		qDebug() << QString("recv msg:[%1]").arg(QString::fromStdString(tm.type()));

		m_buf.remove(0, size);


	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值