2013-04-09 70 views
5

我想實現一個停止和等待算法。我在發件人實現超時時遇到問題。在等待來自reciever的ACK時,我正在使用recvfrom()函數。然而,這使程序空閒,我不能按照超時重新發送。停止和等待算法的Python實現

這裏是我的代碼:

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() 

回答

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() 
+0

你真的不應該用一個空except子句,除非你重新拋出異常。你知道這將是一個socket.timeout,爲什麼不抓住那個? – drxzcl 2013-04-09 19:29:42

+0

@drxzcl剛剛添加了那個;) – cmd 2013-04-09 19:34:27

+0

'雖然沒有確認'而不是'確認'或我錯過了什麼? – mtahmed 2013-12-16 04:53:38