C++ 应用程序无法接收来自 C# 应用程序的连续消息

标签 c++ protocol-buffers

我的问题是当我这样做的时候

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.

我发现您的代码中缺少这些:

  1. 处理两个公告在第一次调用时已在缓冲区中的情况。
  2. 调用 coded_input.Skip()(如果使用正确,应该覆盖上面的#1)
  3. 错误处理(包括调用时缓冲区中还没有公告的情况)。

我猜你的问题是由上面的 #3 引起的,但在我看到 ParseFromArray 代码之前我不确定。

关于C++ 应用程序无法接收来自 C# 应用程序的连续消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394862/

相关文章:

c++ - QT - 如何从组合框中检索 QVariant 值?

java - java中的protobuf是线程安全的吗?

json - 在 golang 中存储和检索接口(interface)

java - 如何打印枚举名称而不是 Protocol Buffer 的 int 值(Java)

c++ - 需要帮助理解 lowByte 和 highByte

c++ - 如何在 C++ 中正确访问 unsigned char 指针的数据?

c++ - 如何在 Windows 中获取登录用户的 SID

c++ - webrtc 视频编码器通过 sdp 同步

c++ - 在 C++ 中解析 Protocol Buffer

java - Protocol Buffer Java,序列化具有字段的枚举