-
Notifications
You must be signed in to change notification settings - Fork 16
/
a2sasync.py
95 lines (76 loc) · 2.99 KB
/
a2sasync.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
import asyncio
import logging
from a2s.exceptions import BrokenMessageError
from a2s.a2sfragment import decode_fragment
HEADER_SIMPLE = b"\xFF\xFF\xFF\xFF"
HEADER_MULTI = b"\xFE\xFF\xFF\xFF"
logger = logging.getLogger("a2s")
class A2SProtocol(asyncio.DatagramProtocol):
def __init__(self):
self.recv_queue = asyncio.Queue()
self.error_event = asyncio.Event()
self.error = None
self.fragment_buf = []
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, packet, addr):
header = packet[:4]
payload = packet[4:]
if header == HEADER_SIMPLE:
logger.debug("Received single packet: %r", payload)
self.recv_queue.put_nowait(payload)
elif header == HEADER_MULTI:
self.fragment_buf.append(decode_fragment(payload))
if len(self.fragment_buf) < self.fragment_buf[0].fragment_count:
return # Wait for more packets to arrive
self.fragment_buf.sort(key=lambda f: f.fragment_id)
reassembled = b"".join(
fragment.payload for fragment in self.fragment_buf)
logger.debug("Received %s part packet with content: %r",
len(self.fragment_buf), reassembled)
self.recv_queue.put_nowait(reassembled)
self.fragment_buf = []
else:
self.error = BrokenMessageError(
"Invalid packet header: " + repr(header))
self.error_event.set()
def error_received(self, exc):
self.error = exc
self.error_event.set()
def raise_on_error():
error = self.error
self.error = None
self.error_event.clear()
raise error
class A2SStreamAsync:
def __init__(self, transport, protocol, timeout):
self.transport = transport
self.protocol = protocol
self.timeout = timeout
def __del__(self):
self.close()
@classmethod
async def create(cls, address, timeout):
loop = asyncio.get_running_loop()
transport, protocol = await loop.create_datagram_endpoint(
lambda: A2SProtocol(), remote_addr=address)
return cls(transport, protocol, timeout)
def send(self, payload):
packet = HEADER_SIMPLE + payload
self.transport.sendto(packet)
async def recv(self):
queue_task = asyncio.create_task(self.protocol.recv_queue.get())
error_task = asyncio.create_task(self.protocol.error_event.wait())
done, pending = await asyncio.wait({queue_task, error_task},
timeout=self.timeout, return_when=asyncio.FIRST_COMPLETED)
for task in pending: task.cancel()
if error_task in done:
self.protocol.raise_on_error()
if not done:
raise asyncio.TimeoutError()
return queue_task.result()
async def request(self, payload):
self.send(payload)
return await self.recv()
def close(self):
self.transport.close()