Python implementation for the Stop and Wait algorithm

I am trying to implement a stop and wait algorithm. I have a problem with the sender's timeout implementation. Waiting for ACK from the receiver, I use the recvfrom () function. However, this makes the program inactive, and I cannot follow the timeout for retransmission.

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()
+5
source share
1 answer

default socket blocks. To control this action, use the funcitons socket setblocking () or settimeout ().

if you want to make your own time.

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()
+1
source

All Articles