-
Notifications
You must be signed in to change notification settings - Fork 9
/
dwsocket.py
executable file
·364 lines (319 loc) · 11 KB
/
dwsocket.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# !/usr/local/bin/python
import socket
import threading
from dwio import DWIO
import time
import select
from dwlib import canonicalize
class DWSocket(DWIO):
def __init__(self, host='localhost', port=6809, conn=None, addr=None, debug=False):
DWIO.__init__(self, threaded=True)
self.host = host
self.port = int(port)
self.conn = conn
if self.conn:
self.sock = self.conn
else:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.addr = addr
self.binding = None
self.debug = debug
def _print(self, msg):
if self.debug:
print(msg)
def name(self):
return "%s %s:%s" % (self.__class__, self.host, self.port)
def isConnected(self):
return self.conn is not None
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.sock.connect((self.host, self.port))
self._print("socket: %s: connecting to %s:%s" % (self, self.host, self.port))
self.conn = self.sock
def _read(self, count=256):
data = None
if self.abort or not self.conn:
return ''
ri = []
try:
(ri, _, _) = select.select([self.conn.fileno()], [], [], 1)
except Exception as e:
print(str(e))
raise Exception("%s: _read (1): Connection closed" % self)
self._close()
if any(ri):
# print "dwsocket: reading"
data = self.conn.recv(count)
# else:
# print "dwsocket: waiting"
if data == '':
raise Exception("%s: _read (2): Connection closed" % self)
self._close()
# if data:
# print "r",data
if self.debug and data is not None:
self._print("\n< socket read: %s: %s" % (self, canonicalize(data)))
return data
def _write(self, data):
if self.abort or not self.conn:
return -1
n = 0
wi = []
try:
(_, wi, _) = select.select([], [self.conn.fileno()], [], 1)
except Exception as e:
print(str(e))
raise Exception("%s: _write: Connection closed" % self)
self._close()
n = -1
if any(wi):
try:
n = self.conn.send(data)
if self.debug:
self._print("\n> socket write: %s: %s" % (self, canonicalize(data)))
except Exception as e:
print(str(e))
self._close()
n = -1
return n
def _in_waiting(self):
if self.abort or not self.conn:
return False
ri = []
try:
(ri, _, _) = select.select([self.conn.fileno()], [], [], 1)
except Exception as e:
print(str(e))
self._print("Connection closed: %s" % self)
self._close()
return any(ri)
# return self.sock.in_waiting
def _out_waiting(self):
if self.abort or not self.conn:
return False
wi = []
try:
(_, wi, _) = select.select([], [self.conn.fileno()], [], 1)
except Exception as e:
print str(e)
# print "Connection closed",self
# self._close()
return any(wi)
# return self.sock.in_waiting
def _close(self):
# if not self.conn:
# return
ri = wi = []
try:
(ri, wi, _) = select.select(
[self.conn.fileno()], [self.conn.fileno()], [], 0)
except Exception as e:
pass
# print str(e)
# print "Connection closed"
if any(ri + wi):
self._print("Closing: connection: %s" % self)
try:
# self.conn.shutdown(socket.SHUT_RDWR)
self.conn.close()
except BaseException:
pass
# if any(wi):
# print "Closing socket"
# try:
# self.conn.shutdown(socket.SHUT_RDWR)
# except:
# pass
self.conn = None
# self.abort = True
# self.sock.shutdown(socket.SHUT_RDWR)
def _cleanup(self):
# self.abort = True
self._close()
if self.sock:
self._print("Closing: socket: %s" % self)
try:
self.sock.close()
except BaseException:
pass
self.sock = None
class DWSocketServer(DWSocket):
def __init__(self, host='localhost', port=6809, debug=False, closedCb=None):
DWSocket.__init__(self, host=host, port=port, debug=debug)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('0.0.0.0', self.port))
self.closedCb = closedCb
def accept(self):
while not self.abort:
self.conn = None
try:
r = self.sock.listen(0)
(self.conn, self.addr) = self.sock.accept()
self._print("Accepted Connection: %s" % str(self.addr))
except Exception as ex:
print("Server Aborted", str(ex))
if self.conn:
break
if not self.sock:
print("accept: No Socket")
self.conn = None
self.abort = True
break
self._print("accept: looping")
def _read(self, count=256):
data = None
if not self.conn:
self._print("accepting")
self.accept()
data = ''
try:
data = DWSocket._read(self, count)
except Exception as e:
print(str(e))
self.conn.close()
self.conn = None
if self.closedCb:
print("%s: Calling callback: %s" % (self, self.closedCb))
self.closedCb(self)
return data
class DWSocketListener(DWSocket):
def __init__(self, host='localhost', port=6809, acceptCb=None, debug=False):
DWSocket.__init__(self, host=host, port=port, debug=debug)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('0.0.0.0', self.port))
self.connections = []
self.at = threading.Thread(target=self._accept, args=())
self.at.daemon = True
def registerCb(self, cb):
self._print("%s: Callback registration: %s" % (self, cb))
self.acceptCb = cb
def accept(self):
raise Exception("Oppps, don't call me")
def _accept(self):
try:
print("%s: Listening on: %s" % (self, self.port))
r = self.sock.listen(0)
fd = self.sock.fileno()
while not self.abort:
ri = []
# print "select: %s" % fd
(ri, _, _) = select.select([fd], [], [], 1)
if any(ri):
try:
(sock, addr) = self.sock.accept()
print("%s: Accepted Connection: %s" % (self, str(addr)))
conn = DWSocket(conn=sock, port=self.port, addr=addr)
self.connections.append(conn)
if self.acceptCb:
self._print("%s: Calling Callback: %s" % (self, self.acceptCb))
self.acceptCb(conn)
except Exception as ex:
print("Listener socket failure, port=%s" % (self.port, str(ex)))
except Exception as ex:
print("Server Aborted, port=%s" % self.port, str(ex))
finally:
self._close()
self.sock.close()
def _close(self):
self.connected = False
self.abort = True
self._print("%s: Closing up shop port=%s" % (self, self.port))
for c in self.connections:
c.close()
class DWSimpleSocket:
def __init__(
self,
host='localhost',
port=6809,
conn=None,
reconnect=False,
debug=False,
closedCb=None):
self.host = host
self.port = int(port)
self.conn = conn
self.connected = False
self.abort = False
if self.conn:
self.sock = self.conn
else:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.reconnect = reconnect
self.debug = debug
self.closedCb = closedCb
def name(self):
return "%s %s:%s" % (self.__class__, self.host, self.port)
def isConnected(self):
return self.conn is not None
def run(self):
pass
def connect(self):
while self.conn is None:
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.sock.connect((self.host, self.port))
print(
"socket: %s: Connected to %s:%s" %
(self, self.host, self.port))
self.conn = self.sock
except BaseException:
if self.reconnect:
time.sleep(1)
else:
raise
def read(self, n=1, timeout=None):
data = ''
while not self.abort and len(data) < n:
d = self.conn.recv(n - len(data))
while not self.abort and d == '' and self.reconnect:
print("socket: %s: Disconnected" % (self))
self.close()
if self.closedCb:
print("%s: Calling callback: %s" % (self, self.closedCb))
self.closedCb(self)
print(
"socket: %s: Reconnecting to %s:%s" %
(self, self.host, self.port))
self.connect()
d = self.conn.recv(n - len(data))
if d != '':
data += d
return data
def write(self, data):
return self.conn.send(data)
def close(self):
print("socket: %s: Closing" % (self))
if self.conn:
self.conn.close()
self.conn = None
self.connected = False
def cleanup(self):
self.abort = True
self.close()
if __name__ == '__main__':
import sys
sock = DWSocketServer()
def cleanup():
print "main: Closing sockial port."
sock.close()
import atexit
atexit.register(cleanup)
try:
sock.accept()
while True:
print ">",
wdata = raw_input()
sock.write(wdata)
sock.write("\n> ")
# print "main: Wrote %d bytes" % len(wdata)
rdata = sock.readline()
# print "main: Read %d bytes" % len(rdata)
print rdata,
finally:
cleanup()
# vim: ts=4 sw=4 sts=4 expandtab
# vim: ts=4 sw=4 sts=4 expandtab