-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.py
executable file
·52 lines (43 loc) · 1.19 KB
/
client.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
#!/usr/bin/env python3
import select
import socket
import sys
# usage: ./client.py [PORT] [HOST]
if __name__ == "__main__":
if len(sys.argv) == 1:
HOST = ("localhost", 10000)
elif len(sys.argv) == 2:
HOST = ("localhost", int(sys.argv[1]))
else:
HOST = (sys.argv[2], int(sys.argv[1]))
main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
main_socket.connect(HOST)
sys.stdout.write("Connected to " + HOST[0] + ":" + str(HOST[1]) + '\n')
sys.stdout.flush()
except:
sys.stdout.write("Could not connect to " + HOST[0] + ":" + str(HOST[1]) + '\n')
sys.stdout.flush()
exit(2)
while True:
read_buffers = [sys.stdin, main_socket]
try:
read_list, write_list, error_list = select.select(read_buffers, [], [])
for sock in read_list:
if sock == main_socket:
data = sock.recv(4096)
if data:
data = data.decode()
sys.stdout.write(data)
sys.stdout.flush()
else:
print("Disconnected from server!")
exit(2)
else:
msg = sys.stdin.readline()
sys.stdout.write("You> " + msg)
sys.stdout.flush()
main_socket.send(msg.encode())
except KeyboardInterrupt:
print("Disconnected from server!")
exit(1)