udp tcp epoll serv
[socket_samples.git] / epoll / epoll.py
blob1eb1459daa18f8b85f8f53e78241ba02ecdcee9a
1 #! /usr/bin/python
3 """
4 epoll 异步使用
5 """
6 import socket, select
8 EOL1 = b'\n\n'
9 EOL2 = b'\n\r\n'
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)
23 try:
24 connections = {}; requests = {}; responses = {}
25 while True:
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]
50 finally:
51 epoll.unregister(serversocket.fileno())
52 epoll.close()
53 serversocket.close()