gconn
gconn.py — Python Source, 3 KB (3624 bytes)
Dateiinhalt
import socket, sys, os from visual import * from threading import * from thread import * import main port = 13372 def getIP(): return socket.gethostbyname(socket.gethostname()) class GameConnection(): def Ssend(self, client, str_): client.send(str(len(str_)) + str_) def Csend(self, str_): self.s.send(str(len(str_)) + str_) def Creceive(self): len_ = self.s.recv(2) print(len_) return self.s.recv(int(len_)) def Sreceive(self, client): len_ = client.recv(2) print(len_) return client.recv(int(len_)) def checkUDP(self): while(True): data_, addr_ = self.udps.recvfrom(4) print("Data_: " + str(data_)) if(data_.startswith("ping")): self.udps.sendto(getIP(), addr_) def __init__(self): # Finde einen Server im Netzwerk, falls nicht vorhanden, starte eigenen self.udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udps.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.udps.sendto("ping", ('<broadcast>', 50001)) self.udps.settimeout(2) data_, addr_ = self.udps.recvfrom(15) print("Data_: (IP) " + str(data_)) self.s.connect((data_, port)) CPacket0x00ConnectRequest(self) self.s.settimeout(3) # Antwort lesen if(CPacket0x00ConnectResponse(self).execute()): # Server hat angenommen print("Server hat angenommen") # TODO Starte Game: startGame() pass else: # Server hat nicht angenommen? print("Fehler bei CPacket0x00ConnectResponse") pass except Exception as e: # TODO entfernen: print(e) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) # Kein Server gefunden # Server starten self.udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udps.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) self.udps.bind(("", 50001)) self.s.bind(('', port)) start_new_thread(self.checkUDP, ()) self.s.listen(1) print("Server gestartet") conn, addr = self.s.accept() print(str(addr)) while(True): SPacket0x00ConnectAccept(self, conn) class Packet(): def __init__(self): pass # Anfrage an Server als neuer User class CPacket0x00ConnectRequest(Packet): def __init__(self, conn): conn.Csend("connect;user=" + str(getIP())) pass # Auswerten der Antwort des Servers als neuer User class CPacket0x00ConnectResponse(Packet): def __init__(self, conn): self.conn = conn pass def execute(self): data = self.conn.Creceive() if(data.startswith("accept")): return True elif(data.startswith("ping")): self.conn.Csend(getIP()) return False else: return False # Server nimmt User an class SPacket0x00ConnectAccept(Packet): def __init__(self, conn, client): data = conn.Sreceive(client) if(data.startswith("connect")): conn.Ssend(client, "accept;user=" + data[data.index("=") + 1:len(data)])