我的问题是当我这样做的时候
TcpClient con = new TcpClient ("127.0.0.1", 5432);
NetworkStream str = con.GetStream ();
Annoucement msg = new Annoucement ();
msg.typ = Annoucement.msgType.NOWY_GRACZ;
Serializer.SerializeWithLengthPrefix (str, msg, PrefixStyle.Base128);
Serializer.SerializeWithLengthPrefix (str, msg, PrefixStyle.Base128);
我尝试接收使用 Protocol Buffer 的自定义库
Connection con = server.accept();
Annoucement ann = con.receive();
cout << ann.typ() << endl;
ann = con.receive();
cout << ann.typ() << endl;
我只能阅读第一个。第二个是错误的,因为字段 typ
设置为 0 而它应该是 3。我认为函数 receive 做错了什么但不知道是什么。
Annoucement Connection::receive() throw(EmptySocket) {
CodedInputStream coded_input(raw_input);
google::protobuf::uint32 n;
coded_input.ReadVarint32(&n);
char *b;
int m;
coded_input.GetDirectBufferPointer((const void**)&b, &m);
Annoucement ann;
ann.ParseFromArray(b, n);
return ann;
}
一个变量在构造函数中被初始化
FileInputStream* raw_input;
raw_input = new FileInputStream(s); //s is socket in this example communication
如何修改它以便我可以从套接字读取连续的消息?
最佳答案
来自reference :
Sets *data to point directly at the unread part of the CodedInputStream's underlying buffer, and *size to the size of that buffer, but does not advance the stream's current position.
This will always either produce a non-empty buffer or return false. If the caller consumes any of this data, it should then call Skip() to skip over the consumed bytes. This may be useful for implementing external fast parsing routines for types of data not covered by the CodedInputStream interface.
我发现您的代码中缺少这些:
- 处理两个公告在第一次调用时已在缓冲区中的情况。
- 调用
coded_input.Skip()
(如果使用正确,应该覆盖上面的#1) - 错误处理(包括调用时缓冲区中还没有公告的情况)。
我猜你的问题是由上面的 #3 引起的,但在我看到 ParseFromArray
代码之前我不确定。
关于C++ 应用程序无法接收来自 C# 应用程序的连续消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394862/