Stop and Wait protocol is a data link layer protocol for transmission of data over noiseless channels. It is a flow control protocol used in noiseless channels. In this article we would code a Python program(Receiver) to implement the stop and wait protocol using sockets and threading.
You can use any code editor you want to run this program. However, using VS Code is recommended.
Let’s look at the receiver’s side (the sender’s side code can be found here):
#make necessary imports
import socket
import random
from ast import literal_eval
#------------------------------------------------------------------------
#create socket object and bind it.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host ="localhost"
port =8000
s.connect((host,port))
#------------------------------------------------------------------------
#take input from user
p_noack = float(input("enter probability of acknowledgement not being sent"))
count = 0
def try_ack(previous, current):
if abs(previous-current) == 1:
return True
else:
return False
l = []
for i in range(0,1000):
l = l +[i]
output = ""
while 2:
data=s.recv(8).decode()
print("Received --> "+data)
datadict = literal_eval(data)
index = list((datadict).keys())[0]
number= random.randint(0,1000)
if count == 0:
count = count +1
current = index
previous = 0
if current == 0:
previous = 1
#simulating the acknowldgement message being lost on the way
else:
count = count +1
previous = current
current = index
print ("p /c :", previous, current)
if try_ack(previous, current):
output = output + list(datadict.values())[0]
#print ("hello", l[number],p_noack*1000 )
if l[number]<(p_noack*1000):
print("Ack not sent")
pass
else:
str="Acknowledgement: Message Received"
#print ("!!!!!!!!!")
#print datadict.values()
s.send(str.encode())
else:
str="Acknowledgement: Message Received"
s.send(str.encode())
print ("indices did not match. Sending ack for previous element")
print ("the received bitstring is",output)
s.close ()
For the sender’s side of the code, go here.
For the github repository, click here.