Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
TCP中没有“消息”这样的东西。它是一个面向流的协议。当然,在较低级别,它是在单独的数据包中传输的,但是您无法控制它,并且您看到的内容可能与这些数据包不同。您只需在任何特定时刻读取接收缓冲区中可用的内容即可。您可能会认为您的消息已被分解,但您也可能会遇到多条消息组合成一个片段到达的情况。
因此,在阅读消息时,您应该使用某种分隔符来确定消息的结束位置,或者使用包含消息长度的标头。如果您发送简单的字符串,将它们编码为 UTF-8 并以空字节终止它们应该可以正常工作。显然,对于更复杂的事情,您需要更复杂的方法。
There is no such thing in TCP as "message". It is a stream-oriented protocol. Of course, at lower levels it is transmitted in separate packets, but you have no way to control it and what you are seeing can be different from those packets. You just read as much as available in the receiving buffer at any particular moment. You may perceive your messages as broken down, but you may as well encounter a situation where several messages arrive as combined into one piece.
So when reading a message you should either use some sort of delimiter to figure out where your message ends, or use a header with message length. If you are sending simple strings, encoding them as UTF-8 and terminating them with null bytes should work fine. For more complicated things you'll need more complicated approach, obviously.
不过关于在消息中添加标题前缀吗?发送带有传输长度和校验和的标头是很常见的。这样您就可以分配适当大小的缓冲区并验证数据完整性。
Though about prefixing your messages with a header? It's very common to send a header with the length and checksum of the transmission. This way you're able to allocate appropriate sized buffers and verify data integrity.
首先发送长度的简单示例。注意:我在读取时检查长度,因为无效的消息长度可能会导致 OutOfMemoryException,这可能会令人困惑/令人震惊。
A simple example of sending the length first. Note: I check the length when reading as an invalid message length can result in an OutOfMemoryException which can be confusing/alarming.