Skip to content

Instantly share code, notes, and snippets.

@GnsP
Created August 17, 2015 10:29
Show Gist options
  • Select an option

  • Save GnsP/ac4f7ddf17fde10d4e6d to your computer and use it in GitHub Desktop.

Select an option

Save GnsP/ac4f7ddf17fde10d4e6d to your computer and use it in GitHub Desktop.
stopAndWait.py
#!/usr/bin/env python
import socket
import os
import sys
PACKET_SIZE = 1024
class Server:
def __init__(self, port, timeout=0.5):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = socket.gethostname()
self.sock.bind((self.host, port))
self.sock.settimeout(timeout)
def run(self):
self.sock.listen(1)
addr = None
dest = None
while addr == None:
try:
dest, addr = self.sock.accept()
except socket.timeout:
pass
print("Connected To ", addr)
user_input = raw_input("--?")
while user_input != "":
size = 0
while size <= 0:
try:
size = self.sock.sendto(user_input, addr)
except socket.timeout:
print("timeout")
print("Data Sent")
ack = False
while not ack:
try:
ACK, address = dest.recv(PACKET_SIZE)
ack = True
except socket.timeout:
self.sock.sendto(user_input, addr)
print(ACK)
user_input = raw_input("--?")
self.sock.close()
class Client:
def __init__(self, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = socket.gethostname()
self.dest = (self.host, port)
self.sock.connect((self.host, port))
def run(self):
while True:
try:
msg, addr = self.sock.recvfrom(PACKET_SIZE)
print("Received :", msg)
if msg == "exit":
break
except:
print("waiting ... ...")
ackSent = False
while not ackSent:
try:
self.sock.sendto(True, self.dest)
ackSent = True
except:
ackSent = False
print("Could not send ACK")
print("ACK SENT")
self.sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment