try import cStringIO as StringIO except ImportError import StringIO im

 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
try:
import cStringIO as StringIO
except ImportError:
import StringIO
import asyncore
import socket
import logging
......
class SCGIHandler(asyncore.dispatcher):
def __init__(self, conn):
asyncore.dispatcher.__init__(self, sock=conn)
self.received_data = StringIO.StringIO()
self.is_writable = False
def writable(self):
return self.received_data.tell() > 0
def handle_write(self):
data = self.received_data.getvalue()
self.send(data)
#self.handle_close()
def handle_read(self):
data = self.recv(16)
print data
#if data == '':
# self.is_writable = True
# print 'writable'
self.received_data.write(data)
def handle_close(self):
self.received_data.close()
self.close()
class AsyncSCGIServer(asyncore.dispatcher):
def __init__(self, ip, port, handler):
asyncore.dispatcher.__init__(self)
self.handler = handler
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((ip, int(port)))
self.listen(500)
print "listening on port", port
def handle_accept(self):
conn, addr = self.accept()
self.handler(conn)
if __name__ == '__main__':
server = AsyncSCGIServer('127.0.0.1', '9000', SCGIHandler)
asyncore.loop()