通过TCP套接字发送可变长度数据

My application needs to send/receive xml data via a tcp socket. There is no way to include any kind of a fixed-length header containing message length. As far as I understand, data transmitted over tcp can come to the receipient like this.

  1. <messa

  2. ge><content

  3. >hi</content>

  4. </message>

But somehow this never happens meaning that data sent with one Send() operation (assuming it's shorter or equal than socket buffer size) is always read completely with one Receive() operation. Is the above scenario possible given that socket buffers of the endpoints are large enough and never exceeded?

#0

Yes, it is possible.

You really can not assume that the buffer boundaries in the send() operation on one side will match with the ones seen by the corresponding recv() at the other end, even if that appears to be the case most of the time.

For example, if you're sending a lot of data, it's possible that the receiving OS will invoke TCP flow control and the sending OS will only be able to send part of a buffer. Or maybe the underlying network has a packet size limitation that requires things to be split up, or ...

#1

This can easily happen if there is a proxy between. If we assume there is no proxy, the client will receive the same packets as the server sends. If you send data in pieces less than TCP MSS of your link, the client will probably receive it in one piece.

However, I would not rely on this. It is easy to tell the end of an XML message by seeing the close tag (</message>), so it's easy to parse XML from a stream.

#2

You can include the message length in your messages. All you have to do is, when you send the xml msg you prepend it with the msg length in the first 4 bytes and then the xml msg. When you receive you take the first 4 bytes of the stream as the msg length and then read each byte for the xml msg

推荐文章

从概念上讲,在OOP中应该如何构造它?

从概念上讲,在OOP中应该如何构造它?

推荐文章

extjs4桌面-如何设置桌面快捷方式工具提示

extjs4桌面-如何设置桌面快捷方式工具提示

推荐文章

IIS7和使用位置标记的永久重定向web.config文件

IIS7和使用位置标记的永久重定向web.config文件

推荐文章

有人能帮我创建一个linqtoxml查询吗?

有人能帮我创建一个linqtoxml查询吗?

推荐文章

如何在jquerypost中获取HTTP错误响应代码

如何在jquerypost中获取HTTP错误响应代码

推荐文章

无法填充我的视图

无法填充我的视图

推荐文章

可以用opencv读取视频流吗?

可以用opencv读取视频流吗?

推荐文章

如何使用Ruby的“scan”方法使捕获组成为可选的呢?

如何使用Ruby的“scan”方法使捕获组成为可选的呢?

推荐文章

如何触发fancybox gallery打开(用拇指),而不单击拇指?

如何触发fancybox gallery打开(用拇指),而不单击拇指?

推荐文章

主干网.js-这个按钮和事件绑定正确吗?

主干网.js-这个按钮和事件绑定正确吗?

推荐文章

JQuery对话框删除状态图像

JQuery对话框删除状态图像

推荐文章

如何在不破坏用户数据的情况下安装ipa更新

如何在不破坏用户数据的情况下安装ipa更新

推荐文章

从数据库上的所有表重新设定主键

从数据库上的所有表重新设定主键

推荐文章

关闭通过模式段显示的视图

关闭通过模式段显示的视图

推荐文章

合并pdf:s与pdfBox创建一个不必要的大文件

合并pdf:s与pdfBox创建一个不必要的大文件

推荐文章

如何解决“页面未能提供一个有效的管理员列表。”错误时创建一个自己的网站?

如何解决“页面未能提供一个有效的管理员列表。”错误时创建一个自己的网站?