Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 83 lines (71 sloc) 2.368 kB
365d90a initial import
Adam Derewecki authored
1 print "Starting demo EPOLL timeserver..."
2 import datetime
3 import select
4 import socket
5
6 IP_ADDRESS = '0.0.0.0'
7 PORT_NUMBER = 2002
8 VERBOSE = False
9
10 EOL1 = '\n\r'
11 EOL2 = '\n\r\n'
12
13 response = 'HTTP/1.0 200 OK\r\n'
14 response += 'Date: Mon, 1 Jan 1996 01:01:01 GMT\r\n'
15 response += 'Content-Type: text/plain\r\n'
16 response += 'Content-Length: %(contentlength)s\r\n\r\n'
17 response += '%(content)s'
18
19 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
20 server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
21 server_socket.bind((IP_ADDRESS, PORT_NUMBER))
22 server_socket.listen(True)
23 server_socket.setblocking(False)
24 server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
25
26 epoll = select.epoll()
27 epoll.register(server_socket.fileno(), select.EPOLLIN)
28 print "Listening on %s:%s" % (IP_ADDRESS, PORT_NUMBER)
29
30 def epoll_epollin(fileno):
31 requests[fileno] += connections[fileno].recv(1024)
32 if EOL1 in requests[fileno] or EOL2 in requests[fileno]:
33 epoll.modify(fileno, select.EPOLLOUT)
34 #TODO -2 magic number?
35 if VERBOSE:
36 print '-' * 40
37 print requests[fileno].decode()[:-2]
38
39 def epoll_epollout(fileno):
40 byteswritten = connections[fileno].send(responses[fileno])
41 responses[fileno] = responses[fileno][byteswritten:]
42 if len(responses[fileno]) == 0:
43 epoll.modify(fileno, 0)
44 connections[fileno].shutdown(socket.SHUT_RDWR)
45
46 def epoll_hup(fileno):
47 epoll.unregister(fileno)
48 connections[fileno].close()
49 del connections[fileno]
50
51 epoll_func_map = dict([
52 (select.EPOLLIN, epoll_epollin),
53 (select.EPOLLOUT, epoll_epollout),
54 (select.EPOLLHUP, epoll_hup)
55 ])
56
57 def build_response(content):
58 response_dict = {
59 'content': content,
60 'contentlength': len(content)
61 }
62 return response % response_dict
63
64 try:
65 connections, requests, responses = {}, {}, {}
66 while True:
67 events = epoll.poll(1)
68 for fileno, event in events:
69 if fileno == server_socket.fileno():
70 connection, address = server_socket.accept()
71 connection.setblocking(False)
72 epoll.register(connection.fileno(), select.EPOLLIN)
73 connections[connection.fileno()] = connection
74 requests[connection.fileno()] = ''
75 response_msg = "Hello world!"
76 responses[connection.fileno()] = build_response(repr(datetime.datetime.now()))
77 else:
78 epoll_func_map[event](fileno)
79 finally:
80 epoll.unregister(server_socket.fileno())
81 epoll.close()
82 server_socket.close()
Something went wrong with that request. Please try again.