1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-11-28 08:48:48 +02:00
vcmi/proxyServer.py

627 lines
21 KiB
Python
Raw Normal View History

2022-10-23 21:11:19 +02:00
import socket
2022-10-25 03:27:53 +02:00
import re
import uuid
2022-10-26 22:52:39 +02:00
import struct
2022-11-10 00:44:34 +02:00
import logging
2022-10-23 21:11:19 +02:00
from threading import Thread
2022-10-30 20:50:16 +02:00
PROTOCOL_VERSION_MIN = 1
PROTOCOL_VERSION_MAX = 1
2022-10-23 21:11:19 +02:00
# server's IP address
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5002 # port we want to use
2022-11-10 00:44:34 +02:00
#logging
logHandlerHighlevel = logging.FileHandler('proxyServer.log')
logHandlerHighlevel.setLevel(logging.WARNING)
logHandlerLowlevel = logging.FileHandler('proxyServer_debug.log')
logHandlerLowlevel.setLevel(logging.DEBUG)
logging.basicConfig(handlers=[logHandlerHighlevel, logHandlerLowlevel], level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
2022-11-09 18:25:06 +02:00
def receive_packed(sock):
2022-10-26 22:52:39 +02:00
# Read message length and unpack it into an integer
raw_msglen = recvall(sock, 4)
if not raw_msglen:
return None
msglen = struct.unpack('<I', raw_msglen)[0]
# Read the message data
return recvall(sock, msglen)
def recvall(sock, n):
# Helper function to recv n bytes or return None if EOF is hit
data = bytearray()
while len(data) < n:
packet = sock.recv(n - len(data))
if not packet:
return None
data.extend(packet)
return data
2022-10-25 03:27:53 +02:00
class GameConnection:
2022-10-30 20:50:16 +02:00
server: socket # socket to vcmiserver
client: socket # socket to vcmiclient
serverInit = False # if vcmiserver already connected
clientInit = False # if vcmiclient already connected
2022-10-25 03:27:53 +02:00
def __init__(self) -> None:
2022-10-26 22:52:39 +02:00
self.server = None
self.client = None
2022-10-25 03:27:53 +02:00
pass
2022-11-09 18:25:06 +02:00
class Room:
2022-10-30 20:50:16 +02:00
total = 1 # total amount of players
joined = 0 # amount of players joined to the session
password = "" # password to connect
protected = False # if True, password is required to join to the session
name: str # name of session
2022-11-09 18:25:06 +02:00
host: socket # player socket who created the room
2022-10-30 20:50:16 +02:00
players = [] # list of sockets of players, joined to the session
2022-11-09 18:25:06 +02:00
started = False
2022-10-23 21:11:19 +02:00
def __init__(self, host: socket, name: str) -> None:
self.name = name
self.host = host
self.players = [host]
self.joined += 1
def isJoined(self, player: socket) -> bool:
return player in self.players
def join(self, player: socket):
if not self.isJoined(player) and self.joined < self.total:
self.players.append(player)
self.joined += 1
def leave(self, player: socket):
if not self.isJoined(player) or player == self.host:
return
self.players.remove(player)
self.joined -= 1
2022-10-25 03:27:53 +02:00
2022-11-09 18:25:06 +02:00
class Session:
name: str # name of session
host_uuid: str # uuid of vcmiserver for hosting player
clients_uuid: list # list od vcmiclients uuid
players: list # list of sockets of players, joined to the session
connections: list # list of GameConnections for vcmiclient/vcmiserver (game mode)
def __init__(self) -> None:
self.name = ""
self.host_uuid = ""
self.clients_uuid = []
self.connections = []
pass
2022-10-30 20:50:16 +02:00
def addConnection(self, conn: socket, isServer: bool):
2022-10-25 03:27:53 +02:00
#find uninitialized server connection
for gc in self.connections:
if isServer and not gc.serverInit:
gc.server = conn
gc.serverInit = True
if not isServer and not gc.clientInit:
gc.client = conn
gc.clientInit = True
#no existing connection - create the new one
gc = GameConnection()
if isServer:
gc.server = conn
gc.serverInit = True
else:
gc.client = conn
gc.clientInit = True
self.connections.append(gc)
2022-11-10 00:30:51 +02:00
def removeConnection(self, conn: socket):
newConnections = []
for c in self.connections:
if c.server == conn:
c.server = None
c.serverInit = False
if c.client == conn:
c.client = None
c.clientInit = False
if c.server != None or c.client != None:
newConnections.append(c)
self.connections = newConnections
2022-10-25 03:27:53 +02:00
def validPipe(self, conn) -> bool:
for gc in self.connections:
if gc.server == conn or gc.client == conn:
return gc.serverInit and gc.clientInit
return False
def getPipe(self, conn) -> socket:
for gc in self.connections:
if gc.server == conn:
return gc.client
if gc.client == conn:
return gc.server
2022-11-09 18:25:06 +02:00
class Client:
auth: bool
def __init__(self) -> None:
self.auth = False
class ClientLobby(Client):
joined: bool
username: str
room: Room
protocolVersion: int
encoding: str
ready: bool
vcmiversion: str #TODO: check version compatibility
def __init__(self) -> None:
super().__init__()
self.room = None
self.joined = False
self.username = ""
self.protocolVersion = 0
self.encoding = 'utf8'
self.ready = False
self.vcmiversion = ""
class ClientPipe(Client):
apptype: str #client/server
prevmessages: list
session: Session
uuid: str
def __init__(self) -> None:
super().__init__()
self.prevmessages = []
self.session = None
self.apptype = ""
self.uuid = ""
class Sender:
address: str #full client address
client: Client
def __init__(self) -> None:
self.client = None
pass
def isLobby(self) -> bool:
return isinstance(self.client, ClientLobby)
def isPipe(self) -> bool:
return isinstance(self.client, ClientPipe)
2022-10-23 21:11:19 +02:00
# create a TCP socket
s = socket.socket()
# make the port as reusable port
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# bind the socket to the address we specified
s.bind((SERVER_HOST, SERVER_PORT))
# listen for upcoming connections
2022-10-25 03:27:53 +02:00
s.listen(10)
2022-11-10 00:44:34 +02:00
logging.critical(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
# active rooms
rooms = {}
2022-10-23 21:11:19 +02:00
# list of active sessions
2022-11-09 18:25:06 +02:00
sessions = []
# initialize list/set of all connected client's sockets
client_sockets = {}
2022-10-23 21:11:19 +02:00
def handleDisconnection(client: socket):
2022-11-10 00:44:34 +02:00
logging.warning(f"[!] Disconnecting client {client}")
2022-11-09 18:25:06 +02:00
if not client in client_sockets:
return
2022-10-23 21:11:19 +02:00
sender = client_sockets[client]
2022-11-09 18:25:06 +02:00
if sender.isLobby() and sender.client.joined:
if not sender.client.room.started:
if sender.client.room.host == client:
2022-10-25 03:27:53 +02:00
#destroy the session, sending messages inside the function
2022-11-09 18:25:06 +02:00
deleteRoom(sender.client.room)
2022-10-25 03:27:53 +02:00
else:
2022-11-09 18:25:06 +02:00
sender.client.room.leave(client)
sender.client.joined = False
message = f":>>KICK:{sender.client.room.name}:{sender.client.username}"
broadcast(sender.client.room.players, message.encode())
updateStatus(sender.client.room)
updateRooms()
2022-11-10 00:30:51 +02:00
if sender.isPipe() and sender.client.auth:
if sender.client.session in sessions:
sender.client.session.removeConnection(client)
if not len(sender.client.session.connections):
2022-11-10 00:44:34 +02:00
logging.warning(f"[*] Destroying session {sender.client.session.name}")
2022-11-10 00:30:51 +02:00
sessions.remove(sender.client.session)
2022-10-23 21:11:19 +02:00
client.close()
2022-11-09 18:25:06 +02:00
client_sockets.pop(client)
2022-10-23 21:11:19 +02:00
def send(client: socket, message: str):
2022-11-09 18:25:06 +02:00
if client in client_sockets.keys():
sender = client_sockets[client]
2022-10-30 20:50:16 +02:00
client.send(message.encode(errors='replace'))
2022-10-23 21:11:19 +02:00
def broadcast(clients: list, message: str):
for c in clients:
2022-11-09 18:25:06 +02:00
if client_sockets[c].isLobby() and client_sockets[c].client.auth:
send(c, message)
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
def sendRooms(client: socket):
2022-10-25 03:27:53 +02:00
msg2 = ""
counter = 0
2022-11-09 18:25:06 +02:00
for s in rooms.values():
2022-10-25 03:27:53 +02:00
if not s.started:
msg2 += f":{s.name}:{s.joined}:{s.total}:{s.protected}"
counter += 1
msg = f":>>SESSIONS:{counter}{msg2}"
2022-10-23 21:11:19 +02:00
send(client, msg)
2022-11-09 18:25:06 +02:00
def updateRooms():
2022-10-23 21:11:19 +02:00
for s in client_sockets.keys():
2022-11-09 18:25:06 +02:00
sendRooms(s)
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
def deleteRoom(room: Room):
msg = f":>>KICK:{room.name}"
for player in room.players:
client_sockets[player].client.joined = False
msg2 = msg + f":{client_sockets[player].client.username}"
2022-10-23 21:11:19 +02:00
send(player, msg2)
2022-11-10 00:44:34 +02:00
logging.warning(f"[*] Destroying room {room.name}")
2022-11-09 18:25:06 +02:00
rooms.pop(room.name)
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
def updateStatus(room: Room):
msg = f":>>STATUS:{room.joined}"
for player in room.players:
msg += f":{client_sockets[player].client.username}:{client_sockets[player].client.ready}"
broadcast(room.players, msg)
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
def startRoom(room: Room):
room.started = True
session = Session()
session.name = room.name
sessions.append(session)
2022-11-10 00:44:34 +02:00
logging.warning(f"[*] Starting session {session.name}")
2022-10-25 03:27:53 +02:00
session.host_uuid = str(uuid.uuid4())
2022-11-09 18:25:06 +02:00
hostMessage = f":>>HOST:{session.host_uuid}:{room.joined - 1}" #one client will be connected locally
2022-10-26 23:39:57 +02:00
#host message must be before start message
2022-11-09 18:25:06 +02:00
send(room.host, hostMessage)
2022-10-26 23:39:57 +02:00
2022-11-09 18:25:06 +02:00
for player in room.players:
_uuid = str(uuid.uuid4())
session.clients_uuid.append(_uuid)
msg = f":>>START:{_uuid}"
2022-10-25 03:27:53 +02:00
send(player, msg)
2022-11-09 18:25:06 +02:00
#remove this connection
player.close
client_sockets.pop(player)
#this room shall not exist anymore
2022-11-10 00:44:34 +02:00
logging.info(f"[*] Destroying room {room.name}")
2022-11-09 18:25:06 +02:00
rooms.pop(room.name)
2022-10-25 03:27:53 +02:00
2022-11-09 18:25:06 +02:00
def dispatch(cs: socket, sender: Sender, arr: bytes):
2022-10-26 22:52:39 +02:00
if arr == None or len(arr) == 0:
2022-10-23 21:11:19 +02:00
return
2022-10-25 03:27:53 +02:00
#check for game mode connection
2022-10-26 22:52:39 +02:00
msg = str(arr)
if msg.find("Aiya!") != -1:
2022-11-09 18:25:06 +02:00
sender.client = ClientPipe()
2022-11-10 00:44:34 +02:00
logging.debug(" vcmi recognized")
2022-10-26 22:52:39 +02:00
2022-11-09 18:25:06 +02:00
if sender.isPipe():
if sender.client.auth: #if already playing - sending raw bytes as is
sender.client.prevmessages.append(arr)
2022-10-26 22:52:39 +02:00
else:
2022-11-09 18:25:06 +02:00
sender.client.prevmessages.append(struct.pack('<I', len(arr)) + arr) #pack message
2022-11-10 00:44:34 +02:00
logging.debug(" packing message")
2022-10-30 20:50:16 +02:00
#search fo application type in the message
2022-10-26 22:52:39 +02:00
match = re.search(r"\((\w+)\)", msg)
_appType = ''
if match != None:
_appType = match.group(1)
2022-11-09 18:25:06 +02:00
sender.client.apptype = _appType
2022-10-26 22:52:39 +02:00
2022-10-30 20:50:16 +02:00
#extract uuid from message
2022-10-26 22:52:39 +02:00
_uuid = arr.decode()
2022-11-10 00:44:34 +02:00
logging.debug(f" decoding {_uuid}")
2022-11-09 18:25:06 +02:00
if not _uuid == '' and not sender.client.apptype == '':
2022-10-26 22:52:39 +02:00
#search for uuid
2022-11-09 18:25:06 +02:00
for session in sessions:
#verify uuid of connected application
if _uuid.find(session.host_uuid) != -1 and sender.client.apptype == "server":
2022-11-10 00:44:34 +02:00
logging.debug(f" apptype {sender.client.apptype} uuid {_uuid}")
2022-11-09 18:25:06 +02:00
session.addConnection(cs, True)
sender.client.session = session
sender.client.auth = True
#read boolean flag for the endian
# this is workaround to send only one remaining byte
# WARNING: reversed byte order is not supported
sender.client.prevmessages.append(cs.recv(1))
2022-11-10 00:44:34 +02:00
logging.debug(f" binding server connection to session {session.name}")
2022-11-10 00:30:51 +02:00
break
2022-11-09 18:25:06 +02:00
if sender.client.apptype == "client":
for p in session.clients_uuid:
if _uuid.find(p) != -1:
2022-11-10 00:44:34 +02:00
logging.debug(f" apptype {sender.client.apptype} uuid {_uuid}")
2022-11-09 18:25:06 +02:00
#client connection
session.addConnection(cs, False)
sender.client.session = session
sender.client.auth = True
#read boolean flag for the endian
# this is workaround to send only one remaining byte
# WARNING: reversed byte order is not supported
sender.client.prevmessages.append(cs.recv(1))
2022-11-10 00:44:34 +02:00
logging.debug(f" binding client connection to session {session.name}")
2022-11-09 18:25:06 +02:00
break
2022-10-25 03:27:53 +02:00
#game mode
2022-11-09 18:25:06 +02:00
if sender.isPipe() and sender.client.auth and sender.client.session.validPipe(cs):
2022-10-26 22:52:39 +02:00
#send messages from queue
2022-11-09 18:25:06 +02:00
opposite = sender.client.session.getPipe(cs)
for x in client_sockets[opposite].client.prevmessages:
cs.sendall(x)
client_sockets[opposite].client.prevmessages.clear()
2022-10-26 22:52:39 +02:00
2022-11-10 00:44:34 +02:00
for x in sender.client.prevmessages:
opposite.sendall(x)
2022-10-30 20:50:16 +02:00
2022-11-09 18:25:06 +02:00
sender.client.prevmessages.clear()
2022-10-26 22:52:39 +02:00
return
2022-10-30 20:50:16 +02:00
#we are in pipe mode but game still not started - waiting other clients to connect
2022-11-09 18:25:06 +02:00
if sender.isPipe():
2022-11-10 00:44:34 +02:00
logging.debug(f" waiting other clients")
2022-10-25 03:27:53 +02:00
return
2022-11-09 18:25:06 +02:00
#intialize lobby mode
if not sender.isLobby():
2022-10-30 20:50:16 +02:00
if len(arr) < 2:
2022-11-10 00:44:34 +02:00
logging.critical("[!] Error: unknown client tries to connect")
2022-10-30 20:50:16 +02:00
#TODO: block address? close the socket?
return
2022-11-09 18:25:06 +02:00
sender.client = ClientLobby()
2022-10-30 20:50:16 +02:00
# first byte is protocol version
2022-11-09 18:25:06 +02:00
sender.client.protocolVersion = arr[0]
2022-10-30 20:50:16 +02:00
if arr[0] < PROTOCOL_VERSION_MIN or arr[0] > PROTOCOL_VERSION_MAX:
2022-11-10 00:44:34 +02:00
logging.critical(f"[!] Error: client has incompatbile protocol version {arr[0]}")
2022-11-09 18:25:06 +02:00
send(cs, ":>>ERROR:Cannot connect to remote server due to protocol incompatibility")
2022-10-30 20:50:16 +02:00
return
2022-11-09 18:25:06 +02:00
# second byte is an encoding str size
2022-10-30 20:50:16 +02:00
if arr[1] == 0:
2022-11-09 18:25:06 +02:00
sender.client.encoding = "utf8"
2022-10-30 20:50:16 +02:00
else:
if len(arr) < arr[1] + 2:
2022-11-09 18:25:06 +02:00
send(cs, ":>>ERROR:Protocol error")
2022-10-30 20:50:16 +02:00
return
2022-11-09 18:25:06 +02:00
# read encoding string
sender.client.encoding = arr[2:(arr[1] + 2)].decode(errors='ignore')
2022-10-30 20:50:16 +02:00
arr = arr[(arr[1] + 2):]
msg = str(arr)
2022-11-09 18:25:06 +02:00
msg = arr.decode(encoding=sender.client.encoding, errors='replace')
2022-10-23 21:11:19 +02:00
_open = msg.partition('<')
_close = _open[2].partition('>')
if _open[0] != '' or _open[1] == '' or _open[2] == '' or _close[0] == '' or _close[1] == '':
2022-11-10 00:44:34 +02:00
logging.error(f"[!] Incorrect message from {sender.address}: {msg}")
2022-10-23 21:11:19 +02:00
return
_nextTag = _close[2].partition('<')
tag = _close[0]
tag_value = _nextTag[0]
#greetings to the server
if tag == "GREETINGS":
2022-11-09 18:25:06 +02:00
if sender.client.auth:
2022-11-10 00:44:34 +02:00
logging.error(f"[!] Greetings from authorized user {sender.client.username} {sender.address}")
2022-11-09 18:25:06 +02:00
send(cs, ":>>ERROR:User already authorized")
2022-10-23 21:11:19 +02:00
return
2022-10-30 20:50:16 +02:00
if len(tag_value) < 3:
2022-11-09 18:25:06 +02:00
send(cs, f":>>ERROR:Too short username {tag_value}")
2022-10-30 20:50:16 +02:00
return
2022-11-07 00:09:05 +02:00
for user in client_sockets.values():
2022-11-09 18:25:06 +02:00
if user.isLobby() and user.client.username == tag_value:
send(cs, f":>>ERROR:Can't connect with the name {tag_value}. This login is already occpupied")
2022-10-30 20:50:16 +02:00
return
2022-11-10 00:44:34 +02:00
logging.info(f"[*] {sender.address} autorized as {tag_value}")
2022-11-09 18:25:06 +02:00
sender.client.username = tag_value
sender.client.auth = True
sendRooms(cs)
2022-10-23 21:11:19 +02:00
#VCMI version received
2022-11-09 18:25:06 +02:00
if tag == "VER" and sender.client.auth:
2022-11-10 00:44:34 +02:00
logging.info(f"[*] User {sender.client.username} has version {tag_value}")
2022-11-09 18:25:06 +02:00
sender.client.vcmiversion = tag_value
2022-10-23 21:11:19 +02:00
#message received
2022-11-09 18:25:06 +02:00
if tag == "MSG" and sender.client.auth:
message = f":>>MSG:{sender.client.username}:{tag_value}"
if sender.client.joined:
broadcast(sender.client.room.players, message) #send message only to players in the room
2022-10-23 21:11:19 +02:00
else:
2022-11-09 18:25:06 +02:00
targetClients = [i for i in client_sockets.keys() if not client_sockets[i].client.joined]
broadcast(targetClients, message)
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
#new room
if tag == "NEW" and sender.client.auth and not sender.client.joined:
if tag_value in rooms:
2022-10-23 21:11:19 +02:00
#refuse creating game
message = f":>>ERROR:Cannot create session with name {tag_value}, session with this name already exists"
2022-11-09 18:25:06 +02:00
send(cs, message)
2022-10-23 21:11:19 +02:00
return
2022-11-10 02:20:44 +02:00
if tag_value == "" or tag_value.startswith(" ") or len(tag_value) < 3:
#refuse creating game
message = f":>>ERROR:Cannot create session with invalid name {tag_value}"
send(cs, message)
return
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
rooms[tag_value] = Room(cs, tag_value)
sender.client.joined = True
sender.client.ready = False
sender.client.room = rooms[tag_value]
2022-10-23 21:11:19 +02:00
#set password for the session
2022-11-09 18:25:06 +02:00
if tag == "PSWD" and sender.client.auth and sender.client.joined and sender.client.room.host == cs:
sender.client.room.password = tag_value
sender.client.room.protected = bool(tag_value != "")
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
#set amount of players to the new room
if tag == "COUNT" and sender.client.auth and sender.client.joined and sender.client.room.host == cs:
if sender.client.room.total != 1:
2022-10-23 21:11:19 +02:00
#refuse changing amount of players
message = f":>>ERROR:Changing amount of players is not possible for existing session"
2022-11-09 18:25:06 +02:00
send(cs, message)
2022-10-23 21:11:19 +02:00
return
2022-11-10 02:20:44 +02:00
if int(tag_value) < 2 or int(tag_value) > 8:
#refuse and cleanup room
deleteRoom(sender.client.room)
message = f":>>ERROR:Cannot create room with invalid amount of players"
send(cs, message)
return
2022-11-09 18:25:06 +02:00
sender.client.room.total = int(tag_value)
message = f":>>CREATED:{sender.client.room.name}"
send(cs, message)
#now room is ready to be broadcasted
message = f":>>JOIN:{sender.client.room.name}:{sender.client.username}"
send(cs, message)
updateStatus(sender.client.room)
updateRooms()
2022-10-23 21:11:19 +02:00
#join session
2022-11-09 18:25:06 +02:00
if tag == "JOIN" and sender.client.auth and not sender.client.joined:
if tag_value not in rooms:
message = f":>>ERROR:Room with name {tag_value} doesn't exist"
send(cs, message)
2022-10-23 21:11:19 +02:00
return
2022-11-09 18:25:06 +02:00
if rooms[tag_value].joined >= rooms[tag_value].total:
message = f":>>ERROR:Room {tag_value} is full"
send(cs, message)
2022-10-23 21:11:19 +02:00
return
2022-11-09 18:25:06 +02:00
if rooms[tag_value].started:
2022-10-23 21:11:19 +02:00
message = f":>>ERROR:Session {tag_value} is started"
2022-11-09 18:25:06 +02:00
send(cs, message)
2022-10-23 21:11:19 +02:00
return
2022-11-09 18:25:06 +02:00
sender.client.joined = True
sender.client.ready = False
sender.client.room = rooms[tag_value]
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
if tag == "PSWD" and sender.client.auth and sender.client.joined and sender.client.room.host != cs:
if not sender.client.room.protected or sender.client.room.password == tag_value:
sender.client.room.join(cs)
message = f":>>JOIN:{sender.client.room.name}:{sender.client.username}"
broadcast(sender.client.room.players, message)
updateStatus(sender.client.room)
updateRooms()
2022-10-23 21:11:19 +02:00
else:
2022-11-09 18:25:06 +02:00
sender.client.joined = False
2022-10-23 21:11:19 +02:00
message = f":>>ERROR:Incorrect password"
2022-11-09 18:25:06 +02:00
send(cs, message)
2022-10-23 21:11:19 +02:00
return
#leaving session
2022-11-09 18:25:06 +02:00
if tag == "LEAVE" and sender.client.auth and sender.client.joined and sender.client.room.name == tag_value:
if sender.client.room.host == cs:
2022-10-23 21:11:19 +02:00
#destroy the session, sending messages inside the function
2022-11-09 18:25:06 +02:00
deleteRoom(sender.client.room)
2022-10-23 21:11:19 +02:00
else:
2022-11-09 18:25:06 +02:00
message = f":>>KICK:{sender.client.room.name}:{sender.client.username}"
broadcast(sender.client.room.players, message)
sender.client.room.leave(cs)
sender.client.joined = False
updateStatus(sender.client.room)
updateRooms()
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
if tag == "READY" and sender.client.auth and sender.client.joined and sender.client.room.name == tag_value:
if sender.client.room.joined > 0 and sender.client.room.host == cs:
startRoom(sender.client.room)
updateRooms()
2022-10-23 21:11:19 +02:00
2022-11-09 18:25:06 +02:00
dispatch(cs, sender, (_nextTag[1] + _nextTag[2]).encode())
2022-10-23 21:11:19 +02:00
def listen_for_client(cs):
"""
This function keep listening for a message from `cs` socket
Whenever a message is received, broadcast it to all other connected clients
"""
while True:
try:
# keep listening for a message from `cs` socket
2022-11-09 18:25:06 +02:00
if client_sockets[cs].isPipe() and client_sockets[cs].client.auth:
2022-10-26 22:52:39 +02:00
msg = cs.recv(4096)
else:
2022-11-09 18:25:06 +02:00
msg = receive_packed(cs)
if msg == None or msg == b'':
handleDisconnection(cs)
return
dispatch(cs, client_sockets[cs], msg)
2022-10-23 21:11:19 +02:00
except Exception as e:
# client no longer connected
2022-11-10 00:44:34 +02:00
logging.error(f"[!] Error: {e}")
2022-11-07 00:09:05 +02:00
handleDisconnection(cs)
2022-10-23 21:11:19 +02:00
return
while True:
# we keep listening for new connections all the time
client_socket, client_address = s.accept()
2022-11-10 00:44:34 +02:00
logging.warning(f"[+] {client_address} connected.")
2022-10-23 21:11:19 +02:00
# add the new connected client to connected sockets
2022-11-09 18:25:06 +02:00
client_sockets[client_socket] = Sender()
client_sockets[client_socket].address = client_address
2022-10-23 21:11:19 +02:00
# start a new thread that listens for each client's messages
t = Thread(target=listen_for_client, args=(client_socket,))
# make the thread daemon so it ends whenever the main thread ends
t.daemon = True
# start the thread
t.start()
# close client sockets
for cs in client_sockets:
cs.close()
# close server socket
s.close()