|
1 | | -import asyncio |
2 | 1 | import time |
3 | | -import random |
4 | 2 | import socket |
5 | 3 |
|
6 | 4 | from .app import app |
@@ -37,61 +35,6 @@ def get_ping_reply(data): |
37 | 35 | return b"\x4f\x45\x74\x03" + peer_id + b"\x00\x00\x03" |
38 | 36 |
|
39 | 37 |
|
40 | | -class MinetestProtocol: |
41 | | - def connection_made(self, transport): |
42 | | - self.transport = transport |
43 | | - |
44 | | - def send_original(self): |
45 | | - self.transport.sendto(PING_PACKET) |
46 | | - |
47 | | - self.start = time.time() |
48 | | - |
49 | | - def datagram_received(self, data, addr): |
50 | | - end = time.time() |
51 | | - self.transport.sendto(get_ping_reply(data), addr) |
52 | | - |
53 | | - self.future.set_result(end - self.start) |
54 | | - self.transport.close() |
55 | | - |
56 | | - def connection_lost(self, exc): |
57 | | - if not self.future.done(): |
58 | | - self.future.set_result(None) |
59 | | - |
60 | | - def error_received(self, exc): |
61 | | - self.future.set_result(None) |
62 | | - |
63 | | - |
64 | | -async def ping_server_async(address, sock=None): |
65 | | - loop = asyncio.get_event_loop() |
66 | | - transport, protocol = await loop.create_datagram_endpoint( |
67 | | - MinetestProtocol, |
68 | | - remote_addr=address, |
69 | | - sock=sock) |
70 | | - attempts = 0 |
71 | | - pings = [] |
72 | | - while len(pings) < 3 and attempts - len(pings) < 3: |
73 | | - attempts += 1 |
74 | | - protocol.future = loop.create_future() |
75 | | - try: |
76 | | - # Sleep a bit to spread requests out |
77 | | - await asyncio.sleep(random.random()) |
78 | | - protocol.send_original() |
79 | | - ping = await asyncio.wait_for(asyncio.shield(protocol.future), 2) |
80 | | - if ping is not None: |
81 | | - pings.append(ping) |
82 | | - except asyncio.TimeoutError: |
83 | | - pass |
84 | | - |
85 | | - if len(pings) != 0: |
86 | | - return min(pings) |
87 | | - |
88 | | - return None |
89 | | - |
90 | | - |
91 | | -async def ping_servers_async(addresses): |
92 | | - return await asyncio.gather(*[ping_server_async(a) for a in addresses]) |
93 | | - |
94 | | - |
95 | 38 | def ping_server_addresses(address, port): |
96 | 39 | pings = [] |
97 | 40 | addr_info = get_addr_info(address, port) |
|
0 commit comments