-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.py
83 lines (52 loc) · 2.13 KB
/
client.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
import time
import logging
from asyncore import dispatcher
from config import *
from do import Do
class Client(dispatcher):
def __init__(self, sock, addr, map=None):
dispatcher.__init__(self, sock, map)
self.get_data = self.send_data = 0
self.client_ip, self.client_port = addr
self.client_name = str(self.client_ip) + ":" + str(self.client_port)
self.do = Do(addr)
def _timeout(self): #Reset timeout if get new data or send new data while time goes on
if self.do.timeout is not None:
if time.time() - self.do.timeout >= CLIENT_TIMEOUT:
return True
return False
def handle_close(self):
if DEBUG:
logging.debug('Disconnected from %s client got %i bytes and sent %i bytes', self.client_name, self.get_data, self.send_data)
else:
logging.info('Disconnected from %s client', self.client_name)
self.close()
def handle_read(self):
data = self.recv(BUFSIZE)
if data:
l = len(data)
self.get_data += l
if DEBUG:
logging.debug('Got data from %s client (%i): %s', self.client_name, l, data)
self.do.request(data)
def handle_write(self):
data = self.do.out_buffer
self.do.out_buffer = self.do.out_buffer.replace(data, '')
if data:
l = len(data)
self.send_data += l
if DEBUG:
logging.debug('Sending data to %s client (%i): %s', self.client_name, l, data)
self.send(data)
if self._timeout():
self.handle_close()
def writable(self):
return (not self.connected) or len(self.do.out_buffer) or self._timeout()
def send(self, data):
num_sent = 0
num_sent = dispatcher.send(self, data[:512])
data = data[num_sent:]
self.do.out_buffer = data + self.do.out_buffer
#Check if reading is finished
#if self.do.close_when_done and self.do.out_buffer == '':
# self.handle_close()