2013-04-09 15 views
5

Sto cercando di implementare un algoritmo di stop e attesa. Ho un problema nell'implementare il timeout al mittente. Durante l'attesa di un ACK da ricevitore, sto usando la funzione recvfrom(). Tuttavia ciò rende il programma inattivo e non posso seguire il timeout per ritrasmetterlo.Implementazione Python per Algoritmo Stop e Wait

Ecco il mio codice:

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

risposta

1

prese blocco per default. Utilizzare il socket funcitons setblocking() o settimeout() per controllare questo comportamento.

se si vuole fare il proprio tempismo.

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

ma vorrei fare qualcosa di simile

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

Davvero non si dovrebbe usare un vuoto clausola except, a meno che non si sta rethrowing l'eccezione. Sai che sarà un socket.timeout, quindi perché non catturare solo quello? – drxzcl

+0

@drxzcl ha appena aggiunto che;) – cmd

+0

'while not acknowledged' invece di' while acknowledged' o mi sono perso qualcosa? – mtahmed