giants-stupid-server/giants/masterserver.py

54 lines
2.4 KiB
Python

import socket
from dpnet.packet import Packet
import threading
from utils.logger import setup_logger
logger = setup_logger(__name__)
class MasterServer:
def __init__(self, server):
self.server = server
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.masterserverip = "gckms.no-ip.org"
self.masterserverport = 27900
def register(self):
statsserverthread = threading.Thread(target=self.register_and_run)
statsserverthread.start()
statsserverthread.join()
def register_and_run(self):
self.socket.bind((self.server.listen_ip, 8911))
logger.info("Listening to " + self.server.listen_ip + ":" + str(8911))
logger.info("Registering to Master Server")
self._register()
self.keepalive()
self.handle_packets()
def _register(self):
packet = Packet()
packet.write(("0"+str(self.server.listen_port)).encode("ascii"))
self.socket.sendto(packet.getvalue(), (self.masterserverip, self.masterserverport))
def keepalive(self):
packet = Packet()
packet.write(("1"+str(self.server.listen_port)).encode("ascii"))
self.socket.sendto(packet.getvalue(), (self.masterserverip, self.masterserverport))
def handle_packets(self):
while True:
data, addr = self.socket.recvfrom(1024)
print(addr[0], ":", addr[1], ">", data.hex())
data = Packet(data)
command = data.read().decode("ascii")
print("Received command:", command)
if command == "\\status\\":
resp = Packet()
respstr = "\\gamename\\giants\\gamever\\"+str(self.server.version)+"\\hostname\\" + self.server.name + "\\hostport\\" + str(
self.server.listen_port) + "\\mapname\\" + self.server.currentmap.mapname + "\\gametype\\Capture Smartie with full base\\numplayers\\" + str(
len(self.server.players)) + "\\maxplayers\\" + str(
self.server.maxplayers) + "\\gamemode\\openplaying\\timelimit\\60\\fraglimit\\0\\teamfraglimit\\0\\firstbasecomplete\\0\\player_0\\Amazed\\frags_0\\0\\deaths_0\\0\\ping_0\\0\\team_0\\Green\\final\\\\queryid\\2.1"
resp.putBytes(respstr.encode("ascii"))
self.socket.sendto(resp.getvalue(), addr)
print(addr[0], ":", addr[1], "<", resp.getvalue().hex())