Skip to content

Commit fd0ad89

Browse files
committed
Handled OSErrors
1 parent 0ded8ab commit fd0ad89

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

lyapun/work/server.py

+20-6
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ def __init__(self, host, port):
2222
self._initialize_socket(host, port)
2323

2424
def run_server(self):
25-
self.sock.listen(5)
2625
while not self.do_stop:
2726
try:
2827
conn, addr = self.sock.accept()
@@ -32,6 +31,9 @@ def run_server(self):
3231
pass
3332
except socket.timeout:
3433
pass
34+
except OSError as msg:
35+
logging.error("OSError: %s", msg)
36+
self.stop_server()
3537
self.stop_server()
3638

3739
def stop_server(self):
@@ -46,10 +48,15 @@ def stop_server(self):
4648
signal.signal(signal.SIGINT, self.orig_signal_handler)
4749

4850
def _initialize_socket(self, host, port):
49-
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
50-
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
51-
self.sock.settimeout(1.0)
52-
self.sock.bind((host, port))
51+
try:
52+
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
53+
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
54+
self.sock.settimeout(1.0)
55+
self.sock.bind((host, port))
56+
self.sock.listen(5)
57+
except OSError as msg:
58+
logging.error("OSError: %s", msg)
59+
self.stop_server()
5360

5461
def _handle_client(self, conn, addr):
5562
thread = threading.Thread(
@@ -67,6 +74,9 @@ def _socket_handler(self, conn, addr):
6774
logging.info("Command=%s, data=%s", command, data)
6875
except socket.timeout:
6976
continue
77+
except OSError as msg:
78+
logging.error("OSError: %s", msg)
79+
self.stop_server()
7080
if command == 'connect':
7181
self._send_data_to_socket(conn, 'connected')
7282
elif command == 'ping':
@@ -95,7 +105,11 @@ def _socket_handler(self, conn, addr):
95105
logging.info("Thread off conn=%s", conn)
96106

97107
def _send_data_to_socket(self, conn, data):
98-
conn.sendall(prepare_data_for_sending(data))
108+
try:
109+
conn.sendall(prepare_data_for_sending(data))
110+
except OSError as msg:
111+
logging.error("OSError: %s", msg)
112+
self.stop_server()
99113

100114
def _kill_signal_handler(self, signum, frame):
101115
self.do_stop = True

0 commit comments

Comments
 (0)