-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.py
643 lines (441 loc) · 15.2 KB
/
channel.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# coding=utf-8
import socket
import threading
import uuid
import datetime
import logging.config
# -------短连接--------
class NetServerChannel:
def __init__(self):
pass
def listen(self, ip, port, count):
try:
self.ip = ip
self.port = port
self.m_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.m_socket.bind((ip, port))
self.m_socket.listen(count)
args_param = []
args_param.append(1800000)
kwargs_param = {}
kwargs_param.__setitem__('HZRY', '42000')
kwargs_param.__setitem__('SHXX', '3600000')
thd = threading.Thread(target=self.__work, name='ListenThread', args=args_param, kwargs=kwargs_param)
thd.setDaemon(True)
thd.start()
except Exception as exception:
print exception
finally:
pass
def __work(self, *args, **kwargs):
self.checkLabel = True
while self.checkLabel:
channel, addr_port = self.m_socket.accept()
chat = ChatServer(channel, addr_port)
def addEventHandler(self, function):
NetServerChannel.function = function
def removeEventHandler(self):
if NetServerChannel.function != None:
NetServerChannel.function = None
def sendRec(self, arg):
chat = ChatServer.selectItem(arg.id)
channel = chat.channel
if channel != None:
len_data = len(arg.response_data)
len_str = self.__Int2String(len_data)
data = len_str + arg.response_data
channel.send(data)
def __Int2String(self, count):
str = '%04d' % count
return str
class NetClientChannel:
def __init__(self, ip, port):
self.m_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.ip = ip
self.port = port
def __connection(self):
self.m_socket.connect((self.ip, self.port))
def __close(self):
try:
self.m_socket.close()
except Exception as exception:
pass
finally:
pass
def send(self, data):
result = ''
try:
self.__connection()
count = len(data)
len_str = self.__Int2String(count)
send_data = len_str + data
self.m_socket.send(send_data)
recvcountstr = self.m_socket.recv(4)
recvcount = int(recvcountstr)
shengyu_count = recvcount
recv_data = ''
check = True
while check:
temp_str = self.m_socket.recv(shengyu_count)
recv_data += temp_str
temp_count = len(temp_str)
shengyu_count = shengyu_count - temp_count
if shengyu_count == 0:
check = False
result = recv_data
self.__close()
pass
except Exception as exception:
print exception
finally:
return result
def __Int2String(self, count):
str = '%04d' % count
return str
class ChatServer:
__Map = None
state = 0
__gc_thread = None
channel = object()
def __init__(self, channel, addr_port):
self.ip = addr_port[0]
self.port = addr_port[1]
self.channel = channel
self.id = str(uuid.uuid1())
self.__checkReceive = True
self.initTime = datetime.datetime.now()
if ChatServer.__Map == None:
ChatServer.__Map = {}
tkey = ChatServer.__Map.has_key(self.id)
lok = threading.Lock()
if tkey == False:
lok.acquire()
ChatServer.__Map[self.id] = self
lok.release()
self.state = 1
self.is_error = False
if ChatServer.__gc_thread == None:
ChatServer.__gc_thread = threading.Thread(target=self.__gc_work, name="gc")
ChatServer.__gc_thread.setDaemon(True)
ChatServer.__gc_thread.start()
thd = threading.Thread(target=self.__ReceiveMessage, name="ChatReceive")
thd.setDaemon(True)
thd.start()
def __gc_work(self):
threading._sleep(30)
lok = threading.Lock()
while True:
values = ChatServer.__Map.values()
datetime_now = datetime.datetime.now()
del_objs = list()
del_check = False
for temp in values:
if temp.state == 0:
del_objs.append(temp)
del_check = True
else:
timespan = datetime_now - temp.initTime
xiangcha_second = timespan.total_seconds()
xiangcha_int = int(xiangcha_second)
if xiangcha_int > 600:
del_objs.append(temp)
del_check = True
if del_check == True:
for tmp in del_objs:
lok.acquire()
tmp.close()
ChatServer.__Map.__delitem__(tmp.id)
lok.release()
threading._sleep(10)
pass
def __ReceiveMessage(self):
temp_error_obj = None
while self.__checkReceive:
try:
len_str = self.channel.recv(4)
len_int = int(len_str)
temp_check = True
shengyu_count = len_int
recv_data = ''
while temp_check:
temp_str = self.channel.recv(shengyu_count)
recv_data += temp_str
tmp_count = len(temp_str)
shengyu_count = shengyu_count - tmp_count
if shengyu_count == 0:
temp_check = False
except socket.error as exception:
self.state = 0
temp_error_obj = exception
except Exception as exception:
self.state = 0
temp_error_obj = exception
finally:
eventArgs = EventArgs(self.id, recv_data)
if self.state == 0:
self.close()
self.is_error = True
eventArgs.is_error = True
eventArgs.error_obj = temp_error_obj
args = []
args.append(eventArgs)
self.fireEvent(args)
def fireEvent(self, args):
try:
temp = args[0]
if NetServerChannel.function != None:
NetServerChannel.function(temp)
except Exception as exception:
pass
finally:
pass
def close(self):
try:
self.channel.close()
except Exception as exception:
pass
finally:
self.__checkReceive = False
self.state = 0
@staticmethod
def selectItem(id):
result_channel = None
tkey = ChatServer.__Map.has_key(id)
if tkey == True:
result_channel = ChatServer.__Map[id]
return result_channel
class EventArgs:
def __init__(self, id, data):
self.id = id
self.request_data = data
self.response_data = None
self.is_error = False
self.error_obj = None
# ------订阅/发布 长连接-------
# 发布者
class PublisherObject:
def __init__(self):
pass
def listen(self, ip, port, count):
try:
self.ip = ip
self.port = port
self.m_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.m_socket.bind((ip, port))
self.m_socket.listen(count)
args_param = []
args_param.append(28880000)
kwargs_param = {}
kwargs_param.__setitem__('shxx', 11000)
thd = threading.Thread(target=self.__work, name='ListenThread', args=args_param, kwargs=kwargs_param)
thd.setDaemon(True)
thd.start()
except Exception as exception:
pass
finally:
pass
def __work(self, *args, **kwargs):
self.checkLabel = True
while self.checkLabel:
channel, addr_port = self.m_socket.accept()
chat = ChatObject(channel, addr_port)
def addEventHandler(self, function):
PublisherObject.function = function
def removeEventHandler(self, function):
if PublisherObject.function != None:
PublisherObject.function = None
def send(self, sid, data):
chat = ChatObject.selectItem(sid)
channel = chat.channel
if channel != None:
len_data = len(data)
len_str = self.__Int2String(len_data)
msg = len_str + data
channel.send(msg)
def release(self, sid):
chat = ChatObject.deleteItem(sid)
pass
def __Int2String(self, count):
str = '%04d' % count
return str
class ChatObject:
__Map = {}
state = 0
__gc_thread = None
def __init__(self, channel, addr_port):
self.id = str(uuid.uuid1())
self.ip = addr_port[0]
self.port = addr_port[1]
self.channel = channel
self.__checkReceive = True
self.initTime = datetime.datetime.now()
if ChatObject.__Map == None:
ChatObject.__Map = {}
tkey = ChatObject.__Map.has_key(self.id)
lok = threading.Lock()
if tkey == False:
lok.acquire()
ChatObject.__Map[self.id] = self
lok.release()
self.state = 1
self.is_error = False
thd = threading.Thread(target=self.__ReceiveMessage, name='Chat')
thd.setDaemon(True)
thd.start()
def __ReceiveMessage(self):
temp_error_obj = None
while self.__checkReceive:
recv_data = ''
try:
len_str = self.channel.recv(4)
len_int = int(len_str)
temp_check = True
shengyu_count = len_int
while temp_check:
temp_str = self.channel.recv(shengyu_count)
recv_data += temp_str
tmp_count = len(temp_str)
shengyu_count = shengyu_count - tmp_count
if shengyu_count == 0:
temp_check = False
except Exception as exception:
self.state = 0
temp_error_obj = exception
logger.error(str(exception) + str(": Network Error Device Disconnect"))
finally:
eventObj = EventObject(self.id, recv_data)
if self.state == 0:
self.is_error = True
self.close()
eventObj.is_error = self.is_error
eventObj.error_obj = temp_error_obj
args_param = []
args_param.append(eventObj)
kwargs_param = {}
kwargs_param.__setitem__('njxx', 3000)
kwargs_param.__setitem__('njxx', 8664000)
thd = threading.Thread(target=self.fireEvent, name='fire_Thread', args=args_param, kwargs=kwargs_param)
thd.setDaemon(True)
thd.start()
pass
def fireEvent(self, *args, **kwargs):
temp = args[0]
if PublisherObject.function != None:
PublisherObject.function(temp)
@staticmethod
def selectItem(id):
result_channel = None
tkey = ChatObject.__Map.has_key(id)
if tkey == True:
result_channel = ChatObject.__Map[id]
return result_channel
@staticmethod
def get_all_Items():
lstItems = []
lstItems = ChatObject.__Map.values()
return lstItems
@staticmethod
def deleteItem(id):
tkey = ChatObject.__Map.has_key(id)
if tkey == True:
lok = threading.Lock()
lok.acquire()
ChatObject.__Map.__delitem__(id)
lok.release()
pass
def close(self):
try:
self.channel.close()
except Exception as exception:
pass
finally:
self.__checkReceive = False
self.state = 0
class EventObject:
def __init__(self, id, data):
self.id = id
self.data = data
self.is_error = False
self.error_obj = None
# 订阅者
class SubscriberObject:
def __init__(self):
self.m_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connection(self, ip, port):
self.ip = ip
self.port = port
self.__checkLabel = True
try:
self.m_socket.connect((ip, port))
self.state = 1
except Exception as exception:
self.state = 0
finally:
pass
def close(self):
try:
self.__checkLabel = False
self.state = 0
self.m_socket.close()
except Exception as exception:
pass
finally:
pass
def addEventHandler(self, function):
SubscriberObject.function = function
def removeEventHandler(self):
SubscriberObject.function = None
def asyncReceive(self):
thd = threading.Thread(target=self.__work, name='Chat')
thd.setDaemon(True)
thd.start()
def __work(self):
temp_error_obj = None
while self.__checkLabel:
recv_data = ''
try:
len_str = self.m_socket.recv(4)
len_int = int(len_str)
temp_check = True
shengyu_count = len_int
while temp_check:
temp_str = self.m_socket.recv(shengyu_count)
recv_data += temp_str
tmp_count = len(temp_str)
shengyu_count = shengyu_count - tmp_count
if shengyu_count == 0:
temp_check = False
except Exception as exception:
self.state = 0
temp_error_obj = exception
finally:
eventObj = EventObject("", recv_data)
if self.state == 0:
self.is_error = True
self.close()
eventObj.is_error = self.is_error
eventObj.error_obj = temp_error_obj
args_param = []
args_param.append(eventObj)
kwargs_param = {}
kwargs_param.__setitem__('njxx', 3000)
kwargs_param.__setitem__('njxx', 8664000)
thd = threading.Thread(target=self.fireEvent, name='fire_Thread', args=args_param, kwargs=kwargs_param)
thd.setDaemon(True)
thd.start()
pass
def fireEvent(self, *args, **kwargs):
temp = args[0]
if SubscriberObject.function != None:
SubscriberObject.function(temp)
def send(self, data):
if self.state == 0:
pass
else:
count = len(data)
len_str = self.__Int2String(count)
send_data = len_str + data
self.m_socket.send(send_data)
def __Int2String(self, count):
str = '%04d' % count
return str