dummy_server.py
This file
Path
tests/dummy_server.py
46 lines · 1.3 KiB · Python
Last changed by
Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption3b5d580
History of this fileTake it
1import asyncore
2import threading
3import socket
4
5class HttpServer(threading.Thread):
6 def __init__(self, port):
7 threading.Thread.__init__(self)
8 self.dispatcher = HttpServerDispatcher(port)
9
10 def run(self):
11 asyncore.loop()
12
13 @property
14 def connection_count(self):
15 return self.dispatcher.connection_count
16
17 def close(self):
18 asyncore.close_all()
19
20class HttpServerDispatcher(asyncore.dispatcher):
21 def __init__(self, port):
22 asyncore.dispatcher.__init__(self)
23 self.connected = False
24 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
25 self.bind(('127.0.0.1', port))
26 self.listen(1)
27 self.connection_count = 0
28
29 def handle_accept(self):
30 self.connection_count += 1
31 self.handler = RequestHandler(self.accept()[0])
32
33 def handle_close(self):
34 self.close()
35
36
37class RequestHandler(asyncore.dispatcher_with_send):
38 def __init__(self, sock):
39 asyncore.dispatcher_with_send.__init__(self, sock)
40 self.response = ("HTTP/1.1 200 OK\r\n"
41 "Connection: keep-alive\r\n"
42 "Content-Length: 0\r\n\r\n")
43
44 def handle_read(self):
45 self.recv(1024)
46 self.send(self.response)