10 response
= b
'HTTP/1.0 200 OK\r\nDate: Mon, 1 Jan 1996 01:01:01 GMT\r\n'
11 response
+= b
'Content-Type: text/plain\r\nContent-Length: 13\r\n\r\n'
12 response
+= b
'Hello, world!'
14 serversocket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
15 serversocket
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
, 1)
16 serversocket
.bind(('0.0.0.0', 8080))
17 serversocket
.listen(1)
18 serversocket
.setblocking(0)
20 epoll
= select
.epoll()
21 epoll
.register(serversocket
.fileno(), select
.EPOLLIN
)
24 connections
= {}; requests
= {}; responses
= {}
26 events
= epoll
.poll(1)
27 for fileno
, event
in events
:
28 if fileno
== serversocket
.fileno():
29 connection
, address
= serversocket
.accept()
30 connection
.setblocking(0)
31 epoll
.register(connection
.fileno(), select
.EPOLLIN
)
32 connections
[connection
.fileno()] = connection
33 requests
[connection
.fileno()] = b
''
34 responses
[connection
.fileno()] = response
35 elif event
& select
.EPOLLIN
:
36 requests
[fileno
] += connections
[fileno
].recv(1024)
37 if EOL1
in requests
[fileno
] or EOL2
in requests
[fileno
]:
38 epoll
.modify(fileno
, select
.EPOLLOUT
)
39 print('-'*40 + '\n' + requests
[fileno
].decode()[:-2])
40 elif event
& select
.EPOLLOUT
:
41 byteswritten
= connections
[fileno
].send(responses
[fileno
])
42 responses
[fileno
] = responses
[fileno
][byteswritten
:]
43 if len(responses
[fileno
]) == 0:
44 epoll
.modify(fileno
, 0)
45 connections
[fileno
].shutdown(socket
.SHUT_RDWR
)
46 elif event
& select
.EPOLLHUP
:
47 epoll
.unregister(fileno
)
48 connections
[fileno
].close()
49 del connections
[fileno
]
51 epoll
.unregister(serversocket
.fileno())