-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.py
More file actions
66 lines (53 loc) · 1.69 KB
/
client.py
File metadata and controls
66 lines (53 loc) · 1.69 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
import argparse
import socket
import select
import sys
import struct
import messages
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--node', help='Hostname of node')
parser.add_argument('--port', help='TCP port', type=int)
args = parser.parse_args()
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((args.node, args.port))
# create tcp socket for communication with peers and clients
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.bind(("", args.port))
tcp_socket.listen(10)
except Exception as e:
print("Cannot start client. Reason: %s" % e)
sys.exit(1)
else:
user_input = input("++> ")
if not user_input:
exit(0)
msg = messages.client_message(user_input)
s.sendall(msg)
socks = [sys.stdin.fileno(), tcp_socket, s]
while True:
print('++>', end='')
sys.stdout.flush()
readable = select.select(socks, [], [])[0]
for fd in readable:
if fd is sys.stdin.fileno():
msg = input()
if msg:
s.sendall(messages.client_message(msg))
else:
s.close()
exit(0)
elif fd is tcp_socket:
conn, addr = tcp_socket.accept()
socks.append(conn)
else:
msg = fd.recv(5)
if not msg:
fd.close()
socks = [f for f in socks if f is not fd]
else:
message_len = struct.unpack('!i', msg[1:5])[0]
data = b''
while len(data) < message_len:
data += fd.recv(message_len - len(data))
print(messages._unpack_message(msg + data)[1])