-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncore_echo_server.py
executable file
·65 lines (55 loc) · 2.01 KB
/
asyncore_echo_server.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
#!/usr/bin/env python
# coding: utf-8
import asyncore
import socket
import logging
class EchoServer(asyncore.dispatcher):
def __init__(self,address):
self.logger = logging.getLogger('EchoServer')
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
self.bind(address)
self.address = self.socket.getsockname()
self.logger.debug("binding to %s",self.address)
self.listen(1)
def handle_accept(self):
client_info = self.accept()
self.logger.debug("handle_accept()-> %s",client_info[1])
EchoHandler(sock=client_info[0])
self.handle_close()
def handle_close(self):
self.logger.debug("handle_close")
self.close()
class EchoHandler(asyncore.dispatcher):
def __init__(self,sock,chunk_size=256):
self.chunk_size = chunk_size
self.logger = logging.getLogger("EchoHandler %s" % str(sock.getsockname()))
asyncore.dispatcher.__init__(self,sock=sock)
self.data_to_write = []
def writable(self):
response = bool(self.data_to_write)
self.logger.debug("writable()-> %s",response)
return response
def handle_write(self):
data = self.data_to_write.pop()
sent = self.send(data[:self.chunk_size])
if sent < len(data):
remaining = data[sent:]
self.data_to_write.append(remaining)
self.logger.debug('handle_write() -> (%d) ', sent)
# if not self.writable():
# self.handle_close()
def handle_read(self):
data = self.recv(self.chunk_size)
self.logger.debug('handle_read() -> (%d)', len(data))
self.data_to_write.insert(0,data)
def handle_close(self):
self.logger.debug('handle_close()')
self.close()
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format='%(name)s: %(message)s',
)
address = ("",8080)
server = EchoServer(address)
asyncore.loop()