Keep alive system
This commit is contained in:
parent
f55275a627
commit
e9ef282c95
|
@ -25,8 +25,10 @@ class Client:
|
|||
if self.state == STATE_UNKNOWN:
|
||||
# We are currently unaware if this is a player client or query client, but we got a packet that will be our check to know
|
||||
if packet.startswith(b"SAMP"):
|
||||
await self.client.on_state_change()
|
||||
self.set_state(STATE_QUERY)
|
||||
else:
|
||||
await self.client.on_state_change()
|
||||
self.set_state(STATE_PLAYER)
|
||||
|
||||
await self.client.on_packet(packet)
|
||||
|
|
|
@ -1,9 +1,13 @@
|
|||
import socket
|
||||
import struct
|
||||
import asyncio
|
||||
from time import time
|
||||
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TIMEOUT = 30 # assume connection is closed after 30 seconds if inactivity
|
||||
|
||||
class BaseClient:
|
||||
def __init__(self, server: "__ServerInstance__", ip: str, port: int):
|
||||
self.server = server
|
||||
|
@ -11,10 +15,27 @@ class BaseClient:
|
|||
self.port = port
|
||||
|
||||
self.ip_uint, = struct.unpack(b"<I", bytes(int(x) for x in self.ip.split(".")))
|
||||
|
||||
self.last_active = time()
|
||||
self.keep_alive_task = asyncio.create_task( self.keep_alive() )
|
||||
self.connected = True # keep_alive will set this to False if connection has not been interacted with for a while (allowing server loop to remove their reference)
|
||||
|
||||
async def on_packet(self, packet: bytes):
|
||||
logger.debug("on_packet(%s)" % packet)
|
||||
self.last_active = time()
|
||||
|
||||
async def send(self, packet: bytes):
|
||||
sock: socket.socket = self.server.socket
|
||||
sock.sendto(packet, (self.ip, self.port))
|
||||
sock.sendto(packet, (self.ip, self.port))
|
||||
|
||||
async def on_state_change(self): # Stop the keep alive task as the whole class is being replaced, TODO: Find out if this could be automated with a magic method
|
||||
self.keep_alive_task.cancel()
|
||||
|
||||
async def keep_alive(self):
|
||||
while True:
|
||||
timestamp = time()
|
||||
if self.last_active + TIMEOUT - timestamp < 0:
|
||||
self.connected = False
|
||||
return
|
||||
|
||||
await asyncio.sleep(self.last_active + TIMEOUT - timestamp)
|
||||
|
|
|
@ -22,7 +22,7 @@ class QueryClient(BaseClient):
|
|||
}
|
||||
|
||||
async def on_packet(self, packet: bytes):
|
||||
logger.debug("on_packet(%s)" % packet)
|
||||
await super().on_packet(packet)
|
||||
|
||||
if len(packet) <= 10: # Invalid
|
||||
return
|
||||
|
|
|
@ -12,6 +12,7 @@ class Server:
|
|||
def __init__(self, config: ServerConfig):
|
||||
self.config = config
|
||||
self.clients = {}
|
||||
self.rcon_clients = {}
|
||||
|
||||
async def create_socket(self):
|
||||
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
|
|
Loading…
Reference in New Issue
Block a user