如何处理多部分网络数据块? [英] How to deal with multiple part network chuncks of data?

查看:67
本文介绍了如何处理多部分网络数据块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TCP 为给定的协议编写网络客户端,但我对事物的整体架构存在一些哲学问题.有时可能会发生我没有完整请求数据的情况,我可能需要读取比目前可用的字节多一些的字节,我想有时我可以在我想要的请求之后获得另一个请求的一部分.在这种情况下,通常的做法是什么?

I'm writing a network client for a given protocol using TCP and I'm having having some philosophical issues with the overall architecture of the thing. Sometimes it may happen that I don't have the whole request data and I may need to read a few more bytes than what's available at the moment, and I imagine sometimes I can get parts of another request after the one I want. What's the usual approach in this kind of situations?

推荐答案

TCP 套接字是面向流的.这意味着读取它们与读取文件相同.如果要通过 TCP 传递离散消息,则需要将数据流拆分为消息,就像 换行符 将文本文件拆分为多行一样.这称为框架.

TCP sockets are Stream-Oriented. That means that reading them is the same as reading a file. If you want to pass discrete messages over TCP, you'll need to split the stream of data into messages, just like the new line character splits text files into lines. This is called framing.

有很多方法可以做到这一点,以下是一些示例:

There many ways of doing this, here are some examples:

  1. 一种计数方法——每条消息都以其长度为前缀.说5apple".你先读5",然后你就知道这条消息有多少字节,第6个字节将是下一条消息的第一个字节.如果您的某些消息很长,您可能需要几个长度字节.

  1. A counting approach - each message is prefixed by its length. say "5apple". You read the "5" first, then you know how many bytes are in this message, and that the 6th byte will be the first byte of the next message. You might need several length bytes if some of your messages are long.

分隔符方法 - 有一个特殊字符(比如空)表示一条消息的结束和下一条消息的开始.然后从套接字读取,直到到达此分隔符.但是请注意,您必须确保此字符永远不会出现在您的消息中,因为这会搞砸一切.

A delimiter approach - have a special character (say null) signal the end of one message and the start of the next one. Then just read from the socket until you reach this delimiter. Note however that you have to make sure that this character will never appear WITHIN your messages since that will screw everything up.

固定大小的消息 - 类似于第一种方法,只是长度字段是隐式的.确保您的所有消息都具有固定长度(如果需要,请使用填充),然后每次从套接字读取正确数量的字节.

Fixed size messages - similar to the first approach, only with the length field being implicit. Make sure that all of your messages are have a fixed length (use padding if needed), then just read the correct number of bytes from the socket each time.

这篇关于如何处理多部分网络数据块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆