5
5
6
6
7
7
class SocketClient :
8
- def __init__ (self , sock ):
9
- self .sock = sock
8
+ def __init__ (self ):
10
9
self .txbuff = ''
11
10
self .rxbuff = ''
12
- self .connected = True
13
11
self .connecting = False
14
-
15
- def __init__ (self , address , port ):
16
- self .txbuff = ''
17
- self .rxbuff = ''
18
12
self .connected = False
19
- self .connecting = True
20
13
14
+ def set_sock (self , sock ):
15
+ self .sock = sock
16
+ self .connected = True
17
+
18
+ def connect (self , address , port ):
21
19
self .sock = socket .socket (AF_INET , SOCK_STREAM )
22
20
self .sock .setblocking (0 )
23
21
try :
24
22
self .sock .connect ((address , port ))
25
23
except socket .error , e :
26
24
pass
25
+ self .connecting = True
27
26
28
27
def run (self ):
29
28
if self .connecting :
@@ -103,7 +102,8 @@ def run(self):
103
102
104
103
def connect (self , address , port ):
105
104
# Determine the next id to assign to socket
106
- client = SocketClient (address , port )
105
+ client = SocketClient ()
106
+ client .connect (address , port )
107
107
while self .next_id in self .clients :
108
108
self .next_id = (self .next_id + 1 ) % 256
109
109
self .clients [self .next_id ] = client
@@ -135,7 +135,8 @@ def accept(self):
135
135
# Accept new connections
136
136
(client_sock , address ) = self .server .accept ()
137
137
# IP filtering could be here
138
- client = SocketClient (client_sock )
138
+ client = SocketClient ()
139
+ client .set_sock (client_sock )
139
140
140
141
# Determine the next id to assign to socket
141
142
while self .next_id in self .clients :
@@ -154,6 +155,11 @@ def send(self, id, data):
154
155
self .clients [id ].send (data )
155
156
return True
156
157
158
+ def send_to_all (self , data ):
159
+ for id in self .clients :
160
+ self .send (id , data )
161
+ return True
162
+
157
163
def is_connected (self , id ):
158
164
if not id in self .clients :
159
165
return None
@@ -204,6 +210,11 @@ def run(self, data):
204
210
server .send (id , data [1 :])
205
211
return ''
206
212
213
+ class WRITE_TO_ALL_Command :
214
+ def run (self , data ):
215
+ server .send_to_all (data )
216
+ return ''
217
+
207
218
class READ_Command :
208
219
def run (self , data ):
209
220
id = ord (data [0 ])
@@ -245,6 +256,7 @@ def init(command_processor):
245
256
command_processor .register ('j' , CLOSE_Command ())
246
257
command_processor .register ('c' , CONNECTING_Command ())
247
258
command_processor .register ('C' , CONNECT_Command ())
259
+ command_processor .register ('b' , WRITE_TO_ALL_Command ())
248
260
command_processor .register_runner (server )
249
261
250
262
def test ():
0 commit comments