如何告诉 TCP 服务器特定消息已经结束?
TCP 客户端逐字节发送数据。那么,如何告诉服务器这条消息已经结束,新的消息现在开始呢?
一种方法是修复将作为书签发送的特殊字符,但该字符也可能是消息的一部分,导致混乱。
还有其他最佳出路吗?
TCP client sends data byte by byte. So, how to tell the server that this message has ended and the new message begins now?
One way is to fix a special character that'll be sent as a bookmark, but that character can also be a part of the message causing confusions.
Any other optimum way out?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果消息是二进制的,则不可能使用特殊字符进行分隔编码。标签长度值 (TLV) 编码最适合这种情况。
例如
除此之外,您还可以有不止一种消息类型
If the message is binary, delimited encoding using a special character is not possible. Tag Length Value (TLV) encoding will be best suited for this.
for example
in addition to that, you can have more than one message type
一种可能的方法是,在发送实际消息之前,您可以发送特定消息中的字节数。当接收方收到该数量的字节后,它可以开始接收下一条消息
One possible way can be that before sending the actual message you can send the number of bytes in the particular message. When the receiving side has received that number of bytes it can start receiving next message
查看开源通信框架 networkComms.net 中使用的实现。特别是第 892 行的 IncomingPacketHandleHandOff() 此处。
它保证接收到的第一个字节指定数据包标头的大小(小于 255 字节)。一旦接收到足够的字节以重建标头,就可以检查标头以确定要接收的剩余大小(数据部分)。如果传入字节多于预期的标头和数据部分,您将查看第一个字节并重新开始。
使用书签字符是在网络堆栈的基础级别使用的,但必须谨慎实施以避免进一步的复杂化。
Checkout the implementation used in networkComms.net, the open source communication framework. In particular IncomingPacketHandleHandOff() on line 892 here.
It guarantees that the first byte received specifies the size of a packet header (Less than 255 bytes). Once enough bytes have been received in order to rebuild the header, the header can be inspected to determine remaining size to be received (data section). If you have more incoming bytes than the expected header and data sections you look at the very first byte and start over.
Using bookmarked characters is what is used at the base level of the network stack but must be implemented carefully to avoid further complications.
如果您希望使用字符作为消息结束标记或消息的一部分,则需要使用转义序列。
例如: 使用字符 '$' 结束消息,使用 '%' 进行转义
,
即然后使用 '$' 结束消息
全部或者发送在消息(或消息块)开始处要接收的字节数如果您当时不知道完整消息的长度)。
If you wish to use a character as both the end of message marker or as a part of the message, you need to use an escape sequence.
For example: Use the character '$' to end the message, and '%' to escape
i.e.
then use '$' to end the message
All alternatively send the number of bytes to be received at the start of the messssage (or message chunk if you do not know the lenght of the complete message at that point).