-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver_epoll.py
58 lines (45 loc) · 1.72 KB
/
server_epoll.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
#!/usr/bin/env python
#coding=utf-8
import socket, select
import sys
BUFFER_SIZE = 10240
port = int(sys.argv[1]) if len(sys.argv) > 1 else 5000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', port))
server.listen(1024)
server.setblocking(0)
print('Starting %s on :%d' % ( __file__, port))
epoll = select.epoll()
epoll.register(server.fileno(), select.EPOLLIN)
try:
connections = {}; buffers = {}
while True:
events = epoll.poll(1)
for fileno, event in events:
if fileno == server.fileno():
conn, address = server.accept()
conn.setblocking(0)
epoll.register(conn.fileno(), select.EPOLLIN)
connections[conn.fileno()] = conn
buffers[conn.fileno()] = b''
elif event & select.EPOLLIN:
buffers[fileno] += connections[fileno].recv(BUFFER_SIZE)
if len(buffers[fileno]) == 0:
epoll.modify(fileno, 0)
connections[fileno].shutdown(socket.SHUT_RDWR)
else:
epoll.modify(fileno, select.EPOLLOUT)
elif event & select.EPOLLOUT:
sent = connections[fileno].send(buffers[fileno])
buffers[fileno] = buffers[fileno][sent:]
if len(buffers[fileno]) == 0:
epoll.modify(fileno, select.EPOLLIN | select.EPOLLOUT)
elif event & select.EPOLLHUP:
epoll.unregister(fileno)
connections[fileno].close()
del connections[fileno]
finally:
epoll.unregister(server.fileno())
epoll.close()
server.close()