@@ -22,7 +22,6 @@ def __init__(self, host, port):
22
22
self ._initialize_socket (host , port )
23
23
24
24
def run_server (self ):
25
- self .sock .listen (5 )
26
25
while not self .do_stop :
27
26
try :
28
27
conn , addr = self .sock .accept ()
@@ -32,6 +31,9 @@ def run_server(self):
32
31
pass
33
32
except socket .timeout :
34
33
pass
34
+ except OSError as msg :
35
+ logging .error ("OSError: %s" , msg )
36
+ self .stop_server ()
35
37
self .stop_server ()
36
38
37
39
def stop_server (self ):
@@ -46,10 +48,15 @@ def stop_server(self):
46
48
signal .signal (signal .SIGINT , self .orig_signal_handler )
47
49
48
50
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 ()
53
60
54
61
def _handle_client (self , conn , addr ):
55
62
thread = threading .Thread (
@@ -67,6 +74,9 @@ def _socket_handler(self, conn, addr):
67
74
logging .info ("Command=%s, data=%s" , command , data )
68
75
except socket .timeout :
69
76
continue
77
+ except OSError as msg :
78
+ logging .error ("OSError: %s" , msg )
79
+ self .stop_server ()
70
80
if command == 'connect' :
71
81
self ._send_data_to_socket (conn , 'connected' )
72
82
elif command == 'ping' :
@@ -95,7 +105,11 @@ def _socket_handler(self, conn, addr):
95
105
logging .info ("Thread off conn=%s" , conn )
96
106
97
107
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 ()
99
113
100
114
def _kill_signal_handler (self , signum , frame ):
101
115
self .do_stop = True
0 commit comments