且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不完整的消息(C# TCP/IP 客户端)

更新时间:2021-09-11 22:02:32

TCP is a stream面向连接,而不是面向消息.它没有消息的概念.当您写出序列化字符串时,它只会看到无意义的字节序列.TCP 可以***地将该流分解为多个片段,并且它们将在客户端以这些片段大小的块接收.您可以在另一端重建整个消息.

TCP is a stream-oriented connection, not message-oriented. It has no concept of a message. When you write out your serialized string, it only sees a meaningless sequence of bytes. TCP is free to break up that stream up into multiple fragments and they will be received at the client in those fragment-sized chunks. It is up to you to reconstruct the entire message on the other end.

在您的场景中,通常会发送消息长度前缀.这样,客户端首先读取长度前缀,以便它可以知道传入的消息应该有多大.

In your scenario, one would typically send a message length prefix. This way, the client first reads the length prefix so it can then know how large the incoming message is supposed to be.

我会认真考虑使用类似 Google 的 Protocol Buffers 作为声明您的消息,然后使用大小前缀选项流式传输它们.好消息是您定义了一组消息,然后使用可用的工具 从消息定义中自动生成 C++、Java、C# 等代码.这将有助于在语言之间使用一致的消息传递集.

I would seriously consider using something like Google's Protocol Buffers as a good way of declaring your messages and then streaming them with the size prefix option. The nice thing is that you define your set of messages once and then use the available tools to automatically generate C++, Java, C#, etc code from the message definitions. This will help in having a consistent messaging set that works between languages.