截断二进制指数退避(Truncated Binary Exponential Back—off,TBEB)算法,原理是让发生碰撞的站点在停止发送后,不是立即再发送数据,而是退避一个随机的时间,降低重传时发生冲突的概率。
1.实验思路:
1.退避时间wait_time
从[1,2……,(2^k-1)]随机选择,其中k=min(重传次数,10)。重传推迟所需要的平均时间随重传次数增大(不超过争用期的10倍)也称为动态避让。
backoff = min(2**attempts,max_backoff)
wait_time = random.randint(0,backoff)
2.连续冲突时停止传输
当重传次数达到16次仍不能成功时(打算同时发送的站太多,以至于连续冲突时)停止传输。
max_attempts = 16
while attempts < max_attempts:
3.拥挤程度
success_rate (bool): 通道拥挤状态,True代表一般拥堵,False代表非常拥堵
random.choice([True,False,False,False,success_rate,success_rate])
4.主函数
1.选择拥挤程度
2. 执行截断二进制指数退避函数
2.实验代码:
"""
模拟截断二进制指数避让算法的传输过程
success_rate (bool): 通道拥挤状态,True代表一般拥堵,False代表非常拥堵
"""
import random
def truncated_binary_exponential_backoff(success_rate,can_success):
print("传输开始…")
attempts = 0
max_attempts = 16
max_backoff = 10
while attempts < max_attempts:
backoff = min(2**attempts,max_backoff)
wait_time = random.randint(0,backoff)
print(f"第{attempts+1}次重传:已等待{wait_time}倍基本争用期")
transmit_successs = random.choice([can_success,False,False,False,success_rate,success_rate])
if transmit_successs == True:
print("传输成功!虽然道路拥堵,但使命必达。")
break
else:
print("发生碰撞,等待下一次传输…")
attempts += 1
if attempts >= 16:
print("传输失败已达到16次,停止传输,正在向上级发送报告…")
print("上级:这么拥堵你怎么发报告的?")
if __name__ == "__main__":
print("欢迎来到 —— 截断二进制指数避让模拟")
choice = input("请选择通道拥堵状态:\n1,一般拥堵\n2,非常拥堵\n3,无法传输\n输入选项编号:")
success_rate = False
can_success = True
if choice == '1':
success_rate = True
elif choice == '2':
success_rate = False
else:
can_success = False
input("(输入任意键开始传输)")
truncated_binary_exponential_backoff(success_rate,can_success)