-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
69 lines (62 loc) · 2.01 KB
/
Copy pathclient.py
File metadata and controls
69 lines (62 loc) · 2.01 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
65
66
67
68
69
import socket
import threading
import json
import sys
HOST = '127.0.0.1'
PORT = 9000
class Client:
def __init__(self, name):
self.name = name
self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.conn.connect((HOST, PORT))
print(f'{name} connected')
threading.Thread(target=self.listen, daemon=True).start()
def sub(self, topic):
self.conn.send(json.dumps({
'action': 'sub',
'topic': topic
}).encode())
print(f'{self.name} subscribed to {topic}')
def pub(self, topic, content):
self.conn.send(json.dumps({
'action': 'pub',
'topic': topic,
'content': content
}).encode())
print(f'{self.name} published: {content}')
def listen(self):
while True:
try:
data = self.conn.recv(4096).decode()
if not data:
break
msg = json.loads(data)
print(f'\n[{self.name}] received "{msg["content"]}" on {msg["topic"]}')
print(f'{self.name}> ', end='', flush=True)
except:
break
def shell(self):
print(f'Commands: sub TOPIC | pub TOPIC MSG | quit')
while True:
cmd = input(f'{self.name}> ').strip()
if cmd == 'quit':
break
elif cmd.startswith('sub '):
_, topic = cmd.split(' ', 1)
self.sub(topic)
elif cmd.startswith('pub '):
parts = cmd.split(' ', 2)
if len(parts) == 3:
_, topic, msg = parts
self.pub(topic, msg)
else:
print('Usage: pub TOPIC MESSAGE')
else:
print('Use: sub TOPIC | pub TOPIC MSG | quit')
self.conn.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python3 client.py NAME')
sys.exit(1)
c = Client(sys.argv[1])
c.shell()