Python
3
Вклад в тег
import socket
import threading
import socketserver
class Player:
def __init__(self, id, name):
self.id = id
self.name = name
class TCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
encoding = "utf-8"
data = self.request.recv(1024)
# Дальше мы обрабатываем данные, которые пришли и, например, создаём из них словарь
if len(session.get_players()) < 2:
player = Player(data["id"], data["name"])
session.add_player(player)
self.request.send("Some response".encode(encoding))
else:
self.request.send("Some error data".encode(encoding))
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
class Session(ThreadedTCPServer):
def __init__(self, connection_data, request_handler):
super().__init__(connection_data, request_handler)
self.max_players = 2
self.players = {}
self.over = False
request_handler.session = self
def get_players(self):
return self.players
def add_player(self, player):
if type(player) == Player:
if len(self.players) < self.max_players:
self.players[player.id] = player
else:
raise Exception("Players overflow")
else:
raise TypeError("'player' argument must be a 'Player' type")
def game_over(self):
self.over = True
if __name__ == "__main__":
HOST, PORT = "localhost", 80
session = Session((HOST, PORT), TCPRequestHandler)
with session:
session_thread = threading.Thread(target=session.serve_forever)
session_thread.daemon = True
session_thread.start()
while not session.over:
pass # Заглушка, чтобы сервер работал
session.shutdown()
GOOGLE_APPLICATION_CREDENTIALS = "test.json"
os.putenv("GOOGLE_APPLICATION_CREDENTIALS", "test.json")