连续重传滑动窗口协议实现代码
时间: 2023-05-25 14:03:11 浏览: 103
由于连续重传滑动窗口协议的实现可能有很多细节,因此这里只提供一个简单的示例代码作为参考。
发送方:
```python
from socket import *
# 创建套接字和连接服务器
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(('127.0.0.1', 8888))
# 定义窗口大小和起始序号
WINDOW_SIZE = 3
start_seq_num = 0
# 发送方发送数据的次数
send_times = 10
# 创建数据包
packets = [f"{i}".encode() for i in range(send_times)]
# 记录已发送但未收到确认的数据包
unacknowledged_packets = packets[:WINDOW_SIZE]
# 循环发送数据包
while packets:
# 发送未确认的数据包
for packet in unacknowledged_packets:
client_socket.send(packet)
print(f"send:{packet.decode()}")
# 接收确认,如果有超时则重传
for i in range(WINDOW_SIZE):
try:
# 设置接收超时时间
client_socket.settimeout(1)
data = client_socket.recv(1024)
except timeout:
# 超时了,重传未确认的数据包
print(f"timeout, resend:{unacknowledged_packets[0].decode()}")
client_socket.send(unacknowledged_packets[0])
continue
# 收到确认,从未确认列表中删除
ack = int(data.decode())
print(f"ack:{ack}")
unacknowledged_packets.pop(0)
# 发送下一个数据包
if packets:
packet = packets.pop(0)
unacknowledged_packets.append(packet)
# 关闭套接字
client_socket.close()
```
接收方:
```python
from socket import *
import time
# 创建套接字和绑定端口
server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.bind(('127.0.0.1', 8888))
server_socket.listen(1)
print('The server is ready to receive')
# 接收方接收数据的次数
receive_times = 10
# 定义窗口大小和期望接收的下一个序号
WINDOW_SIZE = 3
expected_seq_num = 0
# 记录已收到但未确认的数据包
unacknowledged_packets = []
# 循环接收数据包并发送确认
while receive_times > 0:
# 接收数据包
connection_socket, address = server_socket.accept()
data = connection_socket.recv(1024)
print(f"receive:{data.decode()}")
# 如果接收到的是期望的数据包,则发送确认
seq_num = int(data.decode())
if seq_num == expected_seq_num:
expected_seq_num += 1
ack = str(seq_num).encode()
connection_socket.send(ack)
print(f"send ack:{ack.decode()}")
# 将已收到但未确认的数据包添加到列表中
unacknowledged_packets.append(data)
# 如果列表中的数据包个数达到窗口大小,则移动窗口并清空列表
if len(unacknowledged_packets) == WINDOW_SIZE:
unacknowledged_packets.clear()
receive_times -= WINDOW_SIZE
print(f"move window, receive_times:{receive_times}")
# 如果接收到的不是期望的数据包,则丢弃并重新发送确认
else:
ack = str(expected_seq_num - 1).encode()
connection_socket.send(ack)
print(f"send ack:{ack.decode()}")
# 延迟一段时间再关闭套接字,模拟网络延迟
time.sleep(0.5)
connection_socket.close()
# 关闭套接字
server_socket.close()
```
阅读全文