📅  最后修改于: 2023-12-03 15:22:31.036000             🧑  作者: Mango
停止和等待协议(Stop-and-Wait Protocol)是一种简单的数据链路层协议,用于在不可靠的信道上进行数据传输。该协议将数据分割为多个固定长度的帧,并逐一发送和接收,每发送一帧,就停止并等待接收方的确认帧,接收方在收到帧后发送确认帧。一旦发送方收到确认帧,就能发送下一帧,而如果发送方在规定时间内未收到确认帧,则重发该帧。
import time
def stop_and_wait(file, frame_size, timeout):
with open(file, 'rb') as f:
data = f.read()
frames = [data[i:i+frame_size] for i in range(0, len(data), frame_size)]
i = 0
while i < len(frames):
frame = frames[i]
send(frame)
start_time = time.time()
while time.time() - start_time < timeout:
recv_frame = receive()
if recv_frame == b'ACK':
i += 1
break
else:
send(frame)
print('File transfer completed')
def send(frame):
print('Sending frame:', frame)
time.sleep(1)
def receive():
# 模拟有50%概率导致丢包的情况
if random.random() > 0.5:
return b'ACK'
else:
return None
stop_and_wait('file.txt', 1024, 0.5)