[docs]defhandshake(self)->None:packet=Connection()packet.write_varint(0)packet.write_varint(self.version)packet.write_utf(self.address.host)packet.write_ushort(self.address.port)packet.write_varint(1)# Intention to query statusself.connection.write_buffer(packet)
[docs]defread_status(self)->JavaStatusResponse:request=Connection()request.write_varint(0)# Request statusself.connection.write_buffer(request)start=perf_counter()response=self.connection.read_buffer()received=perf_counter()ifresponse.read_varint()!=0:raiseIOError("Received invalid status response packet.")try:raw=json.loads(response.read_utf())exceptValueError:raiseIOError("Received invalid JSON")try:returnJavaStatusResponse.build(raw,latency=(received-start)*1000)exceptKeyErrorase:raiseIOError(f"Received invalid status response: {e}")
[docs]deftest_ping(self)->float:request=Connection()request.write_varint(1)# Test pingrequest.write_long(self.ping_token)sent=perf_counter()self.connection.write_buffer(request)response=self.connection.read_buffer()received=perf_counter()ifresponse.read_varint()!=1:raiseIOError("Received invalid ping response packet.")received_token=response.read_long()ifreceived_token!=self.ping_token:raiseIOError(f"Received mangled ping response packet (expected token {self.ping_token}, received {received_token})")return(received-sent)*1000
[docs]classAsyncServerPinger(ServerPinger):def__init__(self,connection:TCPAsyncSocketConnection,address:Address,version:int=47,ping_token:int|None=None,):# We do this to inform python about self.connection type (it's async)super().__init__(connection,address=address,version=version,ping_token=ping_token)# type: ignore[arg-type]self.connection:TCPAsyncSocketConnection
[docs]asyncdefread_status(self)->JavaStatusResponse:request=Connection()request.write_varint(0)# Request statusself.connection.write_buffer(request)start=perf_counter()response=awaitself.connection.read_buffer()received=perf_counter()ifresponse.read_varint()!=0:raiseIOError("Received invalid status response packet.")try:raw=json.loads(response.read_utf())exceptValueError:raiseIOError("Received invalid JSON")try:returnJavaStatusResponse.build(raw,latency=(received-start)*1000)exceptValueErrorase:raiseIOError(f"Received invalid status response: {e}")
[docs]asyncdeftest_ping(self)->float:request=Connection()request.write_varint(1)# Test pingrequest.write_long(self.ping_token)sent=perf_counter()self.connection.write_buffer(request)response=awaitself.connection.read_buffer()received=perf_counter()ifresponse.read_varint()!=1:raiseIOError("Received invalid ping response packet.")received_token=response.read_long()ifreceived_token!=self.ping_token:raiseIOError(f"Received mangled ping response packet (expected token {self.ping_token}, received {received_token})")return(received-sent)*1000