-
Notifications
You must be signed in to change notification settings - Fork 28
/
server_pyev.py
executable file
·138 lines (115 loc) · 4.04 KB
/
server_pyev.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#!/usr/bin/env python
"""
An echo server using pyev.
copied from pyev's document.
"""
import socket
import signal
import weakref
import errno
import logging
import pyev
logging.basicConfig(level=logging.DEBUG)
STOPSIGNALS = (signal.SIGINT, signal.SIGTERM)
NONBLOCKING = (errno.EAGAIN, errno.EWOULDBLOCK)
class Connection(object):
def __init__(self, sock, address, loop):
self.sock = sock
self.address = address
self.sock.setblocking(0)
self.buf = ""
self.watcher = pyev.Io(self.sock._sock, pyev.EV_READ, loop, self.io_cb)
self.watcher.start()
#logging.debug("{0}: ready".format(self))
def reset(self, events):
w = self.watcher
w.stop()
w.set(self.sock, events)
w.start()
def handle_error(self, msg, level=logging.ERROR, exc_info=True):
logging.log(level, "{0}: {1} --> closing".format(self, msg),
exc_info=exc_info)
self.close()
def handle_read(self):
try:
buf = self.sock.recv(1024)
if buf:
self.buf += buf
self.handle_write()
if buf:
self.reset(pyev.EV_READ | pyev.EV_WRITE)
else:
self.handle_error("connection closed by peer", logging.DEBUG, False)
except socket.error as err:
if err.args[0] not in NONBLOCKING:
self.handle_error("error reading from {0}".format(self.sock))
def handle_write(self):
try:
sent = self.sock.send(self.buf)
except socket.error as err:
if err.args[0] not in NONBLOCKING:
self.handle_error("error writing to {0}".format(self.sock))
else :
self.buf = self.buf[sent:]
if not self.buf:
self.reset(pyev.EV_READ)
def io_cb(self, watcher, revents):
if revents & pyev.EV_READ:
self.handle_read()
else:
self.handle_write()
def close(self):
self.sock.close()
self.watcher.stop()
self.watcher = None
#logging.debug("{0}: closed".format(self))
class Server(object):
def __init__(self, address):
self.sock = socket.socket()
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(address)
self.sock.setblocking(0)
self.address = self.sock.getsockname()
self.loop = pyev.default_loop()
self.watchers = [pyev.Signal(sig, self.loop, self.signal_cb)
for sig in STOPSIGNALS]
self.watchers.append(pyev.Io(self.sock._sock, pyev.EV_READ, self.loop,
self.io_cb))
self.conns = weakref.WeakValueDictionary()
def handle_error(self, msg, level=logging.ERROR, exc_info=True):
#logging.log(level, "{0}: {1} --> stopping".format(self, msg),
# exc_info=exc_info)
self.stop()
def signal_cb(self, watcher, revents):
self.stop()
def io_cb(self, watcher, revents):
try:
while True:
try:
sock, address = self.sock.accept()
except socket.error as err:
if err.args[0] in NONBLOCKING:
break
else:
raise
else:
self.conns[address] = Connection(sock, address, self.loop)
except Exception:
self.handle_error("error accepting a connection")
def start(self):
self.sock.listen(1024)
for watcher in self.watchers:
watcher.start()
#logging.debug("{0}: started on {0.address}".format(self))
self.loop.start()
def stop(self):
self.loop.stop(pyev.EVBREAK_ALL)
self.sock.close()
while self.watchers:
self.watchers.pop().stop()
for conn in self.conns.values():
conn.close()
#logging.debug("{0}: stopped".format(self))
if __name__ == "__main__":
server = Server(("", 5000))
server.start()