-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
52 lines (43 loc) · 1.6 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
from socket import socket
from socket import MSG_DONTWAIT
from socket import MSG_PEEK
from threading import Thread
class Client:
def __init__(self, host: str, port: int):
self.is_running = True
self.host = host
self.port = port
self.connection = socket()
def connect(self) -> None:
self.connection.connect((self.host, self.port))
self.start_keyboard_input_thread()
while self.is_connection_up() and self.is_running:
message = self.receive_message()
print(message)
def start_keyboard_input_thread(self) -> None:
keyboard_input_thread = Thread(target=self.keyboard_input, daemon=True)
keyboard_input_thread.start()
def keyboard_input(self) -> None:
while self.is_connection_up() and self.is_running:
message = input()
self.send_message(message)
def send_message(self, message: str) -> None:
self.connection.send(message.encode())
def receive_message(self) -> str:
return self.connection.recv(1024).decode("utf-8")
def shutdown(self) -> None:
self.is_running = False
self.connection.close()
def is_connection_up(self) -> bool:
try:
data = self.connection.recv(16, MSG_DONTWAIT | MSG_PEEK)
if len(data) == 0:
return False
except BlockingIOError:
return True
except ConnectionResetError:
return False
except Exception as e:
print(f"unexpected exception when checking socket is closed: {e}")
return True
return True