-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync_socket.py
38 lines (33 loc) · 1.16 KB
/
async_socket.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
# UDP sockets wrapper from https://www.pythonsheets.com/notes/python-asyncio.html
class AsyncSocket:
def __init__(self, loop, sock):
self.loop = loop
self.sock = sock
def recvfrom(self, n_bytes, fut=None, registed=False):
fd = self.sock.fileno()
if fut is None:
fut = self.loop.create_future()
if registed:
self.loop.remove_reader(fd)
try:
data, addr = self.sock.recvfrom(n_bytes)
except (BlockingIOError, InterruptedError):
self.loop.add_reader(fd, self.recvfrom, n_bytes, fut, True)
else:
fut.set_result((data, addr))
return fut
def sendto(self, data, addr, fut=None, registed=False):
fd = self.sock.fileno()
if fut is None:
fut = self.loop.create_future()
if registed:
self.loop.remove_writer(fd)
if not data:
return
try:
n = self.sock.sendto(data, addr)
except (BlockingIOError, InterruptedError):
self.loop.add_writer(fd, self.sendto, data, addr, fut, True)
else:
fut.set_result(n)
return fut