73 lines
2.4 KiB
Python

import json
import socket
import threading
class Server:
__address:str
__port:str
__socket:socket
__clientThread:threading.Thread
def __init__(self, address:str, port:str):
self.__address = address
self.__port = port
self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.startServer()
# handles starting the server and assigning socket values to the local reference
def startServer(self):
self.__socket.bind(self.__address, self.__port)
self.__socket.listen()
print(f"server started on: {self.__address}:{self.__port}")
# server loop forwards connection to handleConnection
while True:
# accept incoming connection
# TODO: validate this connection is a valid game connection
client_socket, client_address = self.__socket.accept()
# create network thread for connection
self.__clientThread = threading.Thread(target=self.handleConnection, args=(client_socket, client_address))
self.__clientThread.start()
# handles ticking the game loop server side converting data and passing of to the event handler
def handleConnection(self, socket:socket, address):
# states that a connection has been established
print(f"Connected with {address}")
# Communication with client
while True:
data = socket.recv(1024)
if not data:
break
# decode message for handling
message = data.decode()
messageJson = json.loads(message)
if messageJson["user"] in self.__users:
self.handleEvents(messageJson)
else:
break
print(f"received message from {address}: {message}")
# handles passing of event data to the right functions
def handleEvents(self, event):
# decide which event should be performed
if event["event"] == "login":
pass
elif event["event"] == "join_queue":
# count queue
# move start game if 2 players are in the queue
# remove player from the queue once game starts
pass
elif event["event"] == "leave_queue":
# just remove player from the queue
pass
elif event["event"] == "gameAction":
# pass of to own handler function which handles game logic
pass