tav (owner)

Revisions

gist: 229411 Download_button fork
public
Public Clone URL: git://gist.github.com/229411.git
Embed All Files: show embed
evhttp.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
import signal
import socket
import pyev
 
EOL1 = '\n\n'
EOL2 = '\n\r\n'
 
HELLO_WORLD = '\r\n'.join([
    'HTTP/1.1 200 OK', 'Connection: close', 'Content-type: text/html',
    'Server: MicroHTTPServer/0.3', 'Content-Length: 11', '', 'Hello World'
    ])
 
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind(('0.0.0.0', 9090))
serversocket.listen(1024)
serversocket.setblocking(0)
 
IOLoop = pyev.default_loop()
 
def exit_app(watcher, events):
 
    print "Stopping the loop: {0}".format(watcher.loop)
    watcher.loop.unloop()
 
sig_ev = pyev.Signal(signal.SIGINT, IOLoop, exit_app)
sig_ev.start()
 
connections = {}; requests = {}; responses = {}
read_events = {}; write_events = {}
 
def handle_connection(watcher, events):
 
    connection, address = serversocket.accept()
    connection.setblocking(0)
    connection_fd = connection.fileno()
 
    event = read_events[connection_fd] = pyev.Io(connection_fd, pyev.EV_READ, IOLoop, handle_read)
    event.start()
 
    connections[connection_fd] = connection
    requests[connection_fd] = ''
    responses[connection_fd] = HELLO_WORLD
 
def handle_read(watcher, events):
 
    fileno = watcher.fd
    requests[fileno] += connections[fileno].recv(1024)
 
    if EOL1 in requests[fileno] or EOL2 in requests[fileno]:
 
        read_events[fileno].stop()
        del read_events[fileno]
 
        event = write_events[fileno] = pyev.Io(fileno, pyev.EV_WRITE, IOLoop, handle_write)
        event.start()
 
def handle_write(watcher, events):
 
    fileno = watcher.fd
    byteswritten = connections[fileno].send(responses[fileno])
    responses[fileno] = responses[fileno][byteswritten:]
 
    if len(responses[fileno]) == 0:
        write_events[fileno].stop()
        del write_events[fileno]
        connections[fileno].shutdown(socket.SHUT_RDWR)
        del connections[fileno]
        del requests[fileno]
        del responses[fileno]
 
server_event = pyev.Io(serversocket.fileno(), pyev.EV_READ, IOLoop, handle_connection)
server_event.start()
 
try:
    IOLoop.loop()
finally:
serversocket.close()