6

I am trying to implement a stop and wait algorithm. i have a problem in implementing the timeout at the sender. While waiting for an ACK from reciever, i am using the recvfrom() function. However this makes the program idle, and i can't follow the timeout to re transmit.

here is my code:

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 Answer 1

4

sockets block by default. Use the socket funcitons setblocking() or settimeout() to control this behavior.

if you want to do your own timing.

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

but I would do something like

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()
6
  • You really should not use an empty except clause, unless you are rethrowing the exception. You know it will be a socket.timeout, so why not catch just that one?
    – drxzcl
    Apr 9, 2013 at 19:29
  • @drxzcl just added that ;)
    – cmd
    Apr 9, 2013 at 19:34
  • while not acknowledged instead of while acknowledged or did I miss something?
    – mmtauqir
    Dec 16, 2013 at 4:53
  • @mtahmed hmm, wonder why no one noticed that for over 8 months, lol, fixed, thanks.
    – cmd
    Dec 16, 2013 at 16:43
  • Why did you set the timeout outside the while loop, but not right after sending the user_input to the destination?
    – Kale Joe
    Mar 14, 2022 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.