-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientServerSocket_2.py
48 lines (45 loc) · 1.89 KB
/
clientServerSocket_2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import argparse, random, socket, sys
MAX_BYTES = 63535
def server(interface, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((interface, port))
print('Listening at' , sock.getsockname())
while True:
data, address = sock.recvfrom(MAX_BYTES)
if random.random() < 0.5:
print('Pretending to drop packet from {}'.format(address))
continue
text = data.decode('ascii')
print('The client at {} says {!r}'.format(address, text))
message = 'Your data was {} bytes long'.format(len(data))
sock.sendto(message.encode('ascii'), address)
def client(hostname, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
hostname = sys.argv[2]
sock.connect((hostname, port))
print('Client socket name is {}'.format(sock.getsockname()))
delay = 0.1
text = 'This is another message'
data = text.encode('ascii')
while True:
sock.send(data)
print('Waiting up to {} seconds for a reply'.format(delay))
sock.settimeout(delay)
try:
data = sock.recv(MAX_BYTES)
except socket.timeout:
delay *= 2
if delay > 2.0:
raise RuntimeError('May be the server is down?')
else:
break
print('The server says {!r}'.format(data.decode('ascii')))
if __name__ == '__main__':
choices = { 'client' : client, 'server' : server }
parser = argparse.ArgumentParser(description='Send and receive UDP, pretending packets are often dropped')
parser.add_argument('role', choices=choices, help='which role to take')
parser.add_argument('host', help='interface the server listens at; host the client sends to')
parser.add_argument('-p', metavar='PORT', type=int, default=1060, help='UDP port(default 1060)')
args = parser.parse_args()
function = choices[args.role]
function(args.host, args.p)