c++ app can't receive consecutive messages from c# app
My problem is that when I do
TcpClient con = new TcpClient ("127.0.0.1", 5432);
NetworkStream s开发者_运维知识库tr = con.GetStream ();
Annoucement msg = new Annoucement ();
msg.typ = Annoucement.msgType.NOWY_GRACZ;
Serializer.SerializeWithLengthPrefix (str, msg, PrefixStyle.Base128);
Serializer.SerializeWithLengthPrefix (str, msg, PrefixStyle.Base128);
and I try to receive with custom library that uses protocol buffers
Connection con = server.accept();
Annoucement ann = con.receive();
cout << ann.typ() << endl;
ann = con.receive();
cout << ann.typ() << endl;
I can read only the first one. The second is wrong because the field typ
is set to 0 whereas it should be 3. I think that function receive do something wrong but don't know what.
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;
}
one variable is initialised in constructor
FileInputStream* raw_input;
raw_input = new FileInputStream(s); //s is socket in this example communication
How can I modify it so that I can read consecutive messages from the socket?
From the 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.
I see these missing in your code:
- Handling the case where both the announcements are already in the buffer on the first call.
- Calling
coded_input.Skip()
(should cover #1 above if used right) - Error handling (including the case where there are no announcements already in the buffer at the call).
I'm guessing your problem is caused by #3 above, but I'm not sure until I see the ParseFromArray
code.
精彩评论