TCP分片 [英] TCP fragmentation

查看:48
本文介绍了TCP分片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 TCP 提供类似流的数据传输,但主要问题是 - 通过 TCP 发送数据时会发生什么情况?
1. 可以将消息拆分为 N 个块以适应 MTU 大小.
2. 1 次 recv 调用可以读取两条消息.

I know that TCP provides stream-like data transmission, but the main question is - what situations can occur while sending data over TCP?
1. The message can be split to N chunks to fit in MTU size.
2. Two messages can be read in 1 recv call.

还会有下一个情况吗?
MTU,例如 1500 字节.
客户端调用发送 1498 字节数据.
客户端调用发送 100 字节数据.
服务器调用 recv 并接收 1500 字节数据.
服务器调用 recv 并接收 98 字节数据.

Can there be the next situation?
MTU for example 1500 bytes.
Client calls send with 1498 bytes data.
Client calls send with 100 bytes data.
Server calls recv and receives 1500 bytes data.
Server calls recv and receives 98 bytes data.

所以最终的情况是,第二个客户端发送的 2 个字节将在第一个服务器接收中接收.

So it end up with situation when 2 bytes from second client send will be received in first server recv.

我的协议定义为傻瓜:
4 字节 - 数据长度
数据内容.

My protocol defined as foolows:
4 bytes - data length
data content.

我想知道我能想出将 4 个字节(数据长度)分成 2 个块的情况吗?

I wonder can I came up with situation when 4 bytes (data length) will be split into 2 chunks?

推荐答案

是的,可以在任何字节边界上拆分字节流.您当然可以以 8 种不同方式中的任何一种方式拆分 4 字节数据长度标头:

Yes, a stream of bytes may be split on any byte boundary. You certainly can have your 4 byte data length header split in any of 8 different ways:

4
1-3
2-2
3-1
1-1-2
1-2-1
2-1-1
1-1-1-1

其中一些比其他更容易发生,但您必须考虑到它们.可以处理此问题的代码可能如下所示:

Some of these are more likely to occur than others, but you must account for them. Code that could handle this might look something like the following:

unsigned char buf[4];
size_t len = 0;
while (len < sizeof(buf)) {
    ssize_t n = recv(s, buf+len, sizeof(buf)-len, 0);
    if (n < 0) {
        // error handling here
    }
    len += n;
}
length = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

这篇关于TCP分片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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