76 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			76 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
| import threading
 | |
| import os
 | |
| import json
 | |
| from dotenv import load_dotenv
 | |
| 
 | |
| __users:list
 | |
| 
 | |
| # TODO: setup tcp service for authorization
 | |
| 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:
 | |
|             handleEvents(messageJson)
 | |
|         else:
 | |
|             break
 | |
| 
 | |
|         print(f"received message from {address}: {message}")
 | |
| 
 | |
|     # connection is not required anymore and gets closed
 | |
|     socket.close()
 | |
|     print(f"connection closed for {address}")
 | |
| 
 | |
| 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
 | |
| 
 | |
| def main(self):
 | |
|     load_dotenv()
 | |
| 
 | |
|     # retrieves host data from environment
 | |
|     HOST = os.getenv("HOST")
 | |
|     PORT = os.getenv("PORT")
 | |
| 
 | |
|     self.__users = []
 | |
| 
 | |
|     # create tcp socket
 | |
|     server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 | |
| 
 | |
|     # make socket bind connection info and listen for connections
 | |
| 
 | |
|     print(f"authorization server online on {HOST}:{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 = server_socket.accept()
 | |
| 
 | |
|         # create network thread for connection
 | |
|         client_thread = threading.Thread(target=handleConnection, args=(client_socket, client_address))
 | |
|         client_thread.start()
 | |
| 
 | |
| if __name__ == "__main__":
 | |
|     main() |