-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbus_client.py
More file actions
64 lines (56 loc) · 1.63 KB
/
bus_client.py
File metadata and controls
64 lines (56 loc) · 1.63 KB
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
54
55
56
57
58
59
60
61
62
63
64
"""Simple event bus client — receives JSON-lines over TCP or UDP.
Usage:
python bus_client.py tcp 127.0.0.1 9000
python bus_client.py udp 127.0.0.1 9001
"""
import sys
import json
import socket
def listen_tcp(host, port):
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind((host, port))
srv.listen(1)
print(f"TCP listening on {host}:{port} ...")
conn, addr = srv.accept()
print(f"Connected: {addr}")
buf = ''
try:
while True:
data = conn.recv(4096)
if not data:
break
buf += data.decode()
while '\n' in buf:
line, buf = buf.split('\n', 1)
obj = json.loads(line)
print(obj)
except KeyboardInterrupt:
pass
finally:
conn.close()
srv.close()
def listen_udp(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
print(f"UDP listening on {host}:{port} ...")
try:
while True:
data, addr = sock.recvfrom(4096)
obj = json.loads(data.decode())
print(obj)
except KeyboardInterrupt:
pass
finally:
sock.close()
if __name__ == '__main__':
if len(sys.argv) < 4:
print("Usage: python bus_client.py <tcp|udp> <host> <port>")
sys.exit(1)
proto, host, port = sys.argv[1], sys.argv[2], int(sys.argv[3])
if proto == 'tcp':
listen_tcp(host, port)
elif proto == 'udp':
listen_udp(host, port)
else:
print(f"Unknown protocol: {proto}")