【问题标题】:Python implementation for Stop and Wait Algorithm停止和等待算法的 Python 实现
【发布时间】:2013-04-09 17:53:00
【问题描述】:

我正在尝试实现停止等待算法。我在发件人处实施超时时遇到问题。在等待接收者的 ACK 时,我正在使用 recvfrom() 函数。但是,这会使程序空闲,我无法按照超时重新传输。

这是我的代码:

import socket

import time

mysocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)


while True:


   ACK= " "

    userIn=raw_input()
    if not userIn : break
    mysocket.sendto(userIn, ('127.0.0.01', 88))     
    ACK, address = mysocket.recvfrom(1024)    #the prog. is idle waiting for ACK
    future=time.time()+0.5   
    while True:
            if time.time() > future:
                    mysocket.sendto(userIn, ('127.0.0.01', 88))
                    future=time.time()+0.5
            if (ACK!=" "):
                    print ACK
                    break 
mysocket.close()

【问题讨论】:

    标签: python for-loop implementation wait


    【解决方案1】:

    默认情况下会阻塞套接字。使用套接字函数 setblocking() 或 settimeout() 来控制此行为。

    如果你想自己安排时间。

    mysocket.setblocking(0)
    ACK, address = mysocket.recvfrom(1024)
    

    但我会做类似的事情

    import socket
    
    mysocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    mysocket.settimeout(0.5)
    dest = ('127.0.0.01', 88)
    
    user_input = raw_input()
    
    while user_input:
        mysocket.sendto(user_input, dest)     
        acknowledged = False
        # spam dest until they acknowledge me (sounds like my kids)
        while not acknowledged:
            try:
                ACK, address = mysocket.recvfrom(1024)
                acknowledged = True
            except socket.timeout:
                mysocket.sendto(user_input, dest)
        print ACK
        user_input = raw_input()
    
    mysocket.close()
    

    【讨论】:

    • 你真的不应该使用空的 except 子句,除非你重新抛出异常。你知道这将是一个 socket.timeout,那么为什么不抓住那个呢?
    • @drxzcl 刚刚添加了 ;)
    • while not acknowledged 而不是 while acknowledged 还是我错过了什么?
    • @mtahmed 嗯,想知道为什么超过 8 个月没有人注意到这一点,大声笑,已修复,谢谢。
    • 为什么你在while循环之外设置了超时,但不是在发送user_input到目的地之后?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2012-10-07
    相关资源
    最近更新 更多