-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamer.py
53 lines (46 loc) · 1.87 KB
/
streamer.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
49
50
51
52
53
#!/usr/bin/env python3
# Client that sends data then closes the socket, not expecting a reply
import socket
def server(address):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(address)
sock.listen(1)
print('Run this script in another window with -c option to connect')
print('Listening at', sock.getsockname())
sc, sockname = sock.accept()
print('Accepted connection from', sockname)
sc.shutdown(socket.SHUT_WR)
message = b''
while True:
more = sc.recv(8192) # arbitary value of 8k
if not more:
print('Received zero bytes- end of file')
break
print('Received {} bytes'.format(len(more)))
message += more
print('Message:\n{}'.format(message.decode('ascii')))
sc.close()
sock.close()
def client(address):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(address)
sock.shutdown(socket.SHUT_RD)
print('Connected to', sock.getpeername())
print('Client socket name is', sock.getsockname())
sock.sendall(b'Beautiful is better than ugly.\n')
sock.sendall(b'Explicit is better than implicit\n')
sock.sendall(b'Simple is better than complex\n')
sock.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description='Transmit & receive a data stream')
parser.add_argument('hostname', nargs='?', default='127.0.0.1',
help='IP address or hostname (default: %(default)s)')
parser.add_argument('-c', action='store_true', help='run as client')
parser.add_argument('-p', metavar='port', type=int, default=1060,
help='TCP port number (default: %(default)s)')
args = parser.parse_args()
function = client if args.c else server
function((args.hostname, args.p))