lab0到lab4是实现1个TCP协议,关系图如下:
- lab0实现字节流
- lab1实现字符串拼接到字节流
- lab2实现TCP接收方,考虑已经接收的最大序号和接收窗口大小
- lab3实现TCP发送方,考虑丢包和重传
- lab4实现TCP连接
设计
实现要求:
如下图:
- 蓝色部分:已经被用户读取的,这些流不再占用内存,也不需要处理。
- 绿色部分:已经处理好的,不重复不乱序不丢失的字符串,且放置在流中,等待用户读取,这部分用lab0实现的ByteStream变量 _ o u t p u t \_output _output处理;
- 红色部分:是已push但是未处理的多个字符串 _ u n a s s e m b l e d _ b y t e s \_unassembled\_bytes _unassembled_bytes,可能乱序,重复等,需要尽快处理好放到 _ o u t p u t \_output _output中。
-
_
o
u
t
p
u
t
\_output
_output和
u
n
a
s
s
e
m
b
l
e
d
_
b
y
t
e
s
unassembled\_bytes
unassembled_bytes总长度不能超过限制长度
c
a
p
c
i
t
y
capcity
capcity。
使用map来记录未处理字符串的序号和字符串 _ u n a s s e m b l e d _ b y t e s \_unassembled\_bytes _unassembled_bytes,key作为索引,对重复字符串的处理较为方便。用 e x p e c t e d _ i n d e x expected\_index expected_index记录当前按序到达的字符编号。
一. 进行特殊情况处理
- 长度为0的字符串:仅考虑 e o f eof eof
- 被包含在 _ o u t p u t \_output _output中的字符串或者整段字符串超出范围:不必处理
- 部分超出范围的字符串:将超出部分删除
进行特殊情况处理之后,将字符串添加到 _ u n a s s e m b l e d _ b y t e s \_unassembled\_bytes _unassembled_bytes中。
二.将
_
u
n
a
s
s
e
m
b
l
e
d
_
b
y
t
e
s
\_unassembled\_bytes
_unassembled_bytes可合并到
_
o
u
t
p
u
t
\_output
_output进行合并
迭代
_
u
n
a
s
s
e
m
b
l
e
d
_
b
y
t
e
s
\_unassembled\_bytes
_unassembled_bytes,若当前的字符串编号
i
n
d
e
x
index
index不大于
e
x
p
e
c
t
e
d
_
i
n
d
e
x
expected\_index
expected_index则可将其进行合并,注意有3种情况需要考虑:
- 字符串被 _ o u t p u t \_output _output包含
- 字符串部分被 _ o u t p u t \_output _output包含
- 字符串恰好接在 _ o u t p u t \_output _output之后
第2种和第3种在合并到 _ o u t p u t \_output _output之后需要更新 e x p e c t e d _ i n d e x expected\_index expected_index,最后3种情况的字符串均从 _ u n a s s e m b l e d _ b y t e s \_unassembled\_bytes _unassembled_bytes中删除。
三.更新
_
u
n
a
s
s
e
m
b
l
e
d
_
b
y
t
e
s
\_unassembled\_bytes
_unassembled_bytes,并更新总字符数
注意字符串是不能重叠的,更新阶段主要就是处理重复和交叠的情况。为了方便,重新开了一个map变量mp记录更新后的
_
u
n
a
s
s
e
m
b
l
e
d
_
b
y
t
e
s
\_unassembled\_bytes
_unassembled_bytes。因为map会按key排序,所以迭代
_
u
n
a
s
s
e
m
b
l
e
d
_
b
y
t
e
s
\_unassembled\_bytes
_unassembled_bytes时是会按字符串编号从小到大遍历的。记录更新后的最后一个字符串的编号
s
t
a
r
t
_
i
n
d
e
x
start\_index
start_index和字符串尾编号
e
n
d
_
i
n
d
e
x
end\_index
end_index。分为2种情况:
- 当前字符串的编号 i n d e x index index不大于已更新的最后一个字符串的末位编号 e n d _ i n d e x end\_index end_index,则说明当前字符串和已更新字符串有交叠,若不是被完全覆盖,则更新已更新字符串的末位编号,并将当前字符串合并到最新字符串中。
- 若当前字符串和最新字符串无交叠,则更新当前字符串为最新字符串,记录其首编号和末编号。
以上2种情况在更新最新字符串时需要更新一下总字符数。