编译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);
}
}