1
1
import sys
2
+ import time
2
3
3
4
__author__ = 'Oleksandr Korobov'
4
5
@@ -19,34 +20,50 @@ def __start_serve_connection(self, conn, addr):
19
20
self .__clients_pool .append (stw )
20
21
21
22
def __close_all_clients (self ):
22
- for client in self .__clients_pool :
23
- client .close ()
24
- self .__clients_pool .clear ()
23
+ print ('closing ' , len (self .__clients_pool ), 'clients' )
24
+
25
+ while len (self .__clients_pool ) > 0 :
26
+ self .__clients_pool [0 ].close ()
27
+ #self.socket.shutdown(socket.SHUT_RDWR)
28
+ self .socket .close ()
25
29
26
30
def serve (self ):
27
31
self .socket = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
28
32
self .socket .bind ((self .host , self .port ))
29
33
34
+ self .socket .settimeout (2 )
30
35
while not self .closing :
36
+
31
37
self .socket .listen (5 )
32
- conn , addr = self .socket .accept ()
33
- self .__start_serve_connection (conn , addr )
38
+ try :
39
+ conn , addr = self .socket .accept ()
40
+ self .__start_serve_connection (conn , addr )
41
+ except :
42
+ pass # Remove this awful exception swallowing
34
43
self .__close_all_clients ()
35
44
36
45
def stop_serve (self ):
37
46
self .closing = True
38
- print ( 'Proper server closing is not implemented yet...' )
47
+ self . __close_all_clients ( )
39
48
40
49
def notify (self , sender , message ):
41
50
print ('Notification received:' , message )
51
+
42
52
if message ['cmd' ] == 'CMD_BROADCAST' :
43
53
for client in self .__clients_pool :
44
54
if not client is None and not client .closing :
45
55
#print('Posting to '. client.name)
46
56
client .post (message )
57
+
47
58
if message ['cmd' ] == 'CMD_MESSAGE' :
48
59
client .post ({'cmd' : 'CMD_SEVER_WARNING' , 'msg' : 'message sending is not implemented yet' })
49
60
61
+ if message ['cmd' ] == 'CMD_CLIENT_LEFT' :
62
+ print ('Client left' , message ['id' ])
63
+ self .__clients_pool .remove (message ['id' ])
64
+
65
+ if message ['cmd' ] == 'CMD_SCLOSESERVER' :
66
+ self .closing = True
50
67
51
68
chat_sever = ChatServer (PORT = 50007 )
52
69
@@ -57,4 +74,4 @@ def signal_handler(signal, frame):
57
74
58
75
signal .signal (signal .SIGINT , signal_handler )
59
76
60
- chat_sever .serve ()
77
+ chat_sever .serve ()
0 commit comments