forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp-client.py
More file actions
executable file
·65 lines (54 loc) · 1.72 KB
/
Copy pathapp-client.py
File metadata and controls
executable file
·65 lines (54 loc) · 1.72 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
#!/usr/bin/env python3
import sys
import socket
import selectors
import traceback
import libclient
sel = selectors.DefaultSelector()
def create_request(action, value):
if action == 'search':
return dict(
type='text/json',
encoding='utf-8',
content=dict(action=action, value=value)
)
else:
return dict(
type='binary/custom-client-binary-type',
encoding='binary',
content=bytes(action + value, encoding='utf-8')
)
def start_connection(host, port, request):
addr = (host, port)
print('starting connection to', addr)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)
sock.connect_ex(addr)
events = selectors.EVENT_READ | selectors.EVENT_WRITE
message = libclient.Message(sel, sock, addr, request)
sel.register(sock, events, data=message)
if len(sys.argv) != 5:
print('usage:', sys.argv[0], '<host> <port> <action> <value>')
sys.exit(1)
host, port = sys.argv[1], int(sys.argv[2])
action, value = sys.argv[3], sys.argv[4]
request = create_request(action, value)
start_connection(host, port, request)
try:
while True:
events = sel.select(timeout=1)
for key, mask in events:
message = key.data
try:
message.process_events(mask)
except Exception as e:
print('main: error: exception for',
f'{message.addr}:\n{traceback.format_exc()}')
message.close()
# Check for a socket being monitored to continue.
if not sel.get_map():
break
except KeyboardInterrupt:
print('caught keyboard interrupt, exiting')
finally:
sel.close()