-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
52 lines (42 loc) · 1.53 KB
/
server.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
import socket
import threading
class Server():
def __init__(self):
self._socket = None
self._thread_events = {}
self._working = False
def start(self, port, target):
print('Server is not done yet!')
self._working = True
try:
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.bind((target, port))
self._socket.listen(1)
self._accept_connections()
except KeyboardInterrupt:
pass
finally:
self._socket.close()
self._stop_all_threads()
def _accept_connections(self):
while self._working:
client_socket, addr = self._socket.accept()
print('Connection accepted from %s:%d' % addr)
thread_event = threading.Event()
args = (client_socket, thread_event)
client_thread = threading.Thread(target=self._client_handler,
args=args)
client_thread.start()
self._thread_events[addr] = thread_event
def _stop_all_threads(self):
for thread_event in self._thread_events.values():
thread_event.set()
@staticmethod
def _client_handler(client_socket, thread_event):
while not thread_event.is_set():
data = client_socket.recv(1024)
if not data:
break
else:
print('[INFO] Received: %s' % data)
client_socket.sendall(b'\rACK{}\n')