Commit db3f37e8 authored by ZettaScript's avatar ZettaScript
Browse files

Communication & new game

parent 548475ec
......@@ -46,6 +46,15 @@ Le protocole utilisé entre clients et serveur est très simple.
**VERSION** étant la version du protocole utilisée pour le paquet, **LANG** le langage utilisé pour coder les données, **LENGTH** la taille des données, **DATA** les données.
Pour le moment, seul le JSON est utilisé.
Les données JSON comprennent un champ "error".
> 0: OK
> 16: Communication error: decoding header
> 17: Communication error: unsupported protocol version
> 18: Communication error: unknown language
> 19: Communication error: decoding JSON
> 48: Game management error: that game name is already used
> 49: Game management error: miss new game name
## Sources
http://www.trm.creationmonetaire.info/TheorieRelativedelaMonnaie.pdf
......
......@@ -45,6 +45,7 @@ HOST = socket.gethostname() # server host name
PORT = 8651 # server port
games = []
games_index = {}
class Player():
def __init__(self, name, address):
......@@ -63,7 +64,7 @@ class Game():
def __init__(self, name, public, leader_name, leader_address, consts):
# Consts
self.name = name
self.creation_time = time()
self.creation_time = int(time())
self.public = public
self.leader_name = leader_name
self.leader_address = leader_address
......@@ -163,6 +164,12 @@ def readConfig():
for key, value in conf["Game"].items():
CONSTS[key] = value
def sendErrorToClient(client, errcode, resp_lng="json"):
if resp_lng == "json":
resp_raw = json.dumps({"error":errcode}).encode()
client.sendall(resp_raw)
client.close()
"""
Partie serveur en dessous, pas encore complètement fonctionnelle.
"""
......@@ -246,27 +253,25 @@ Options:\n\
else:
break
resp_raw = b""# raw response
resp = {"error":0}# response
resp_lng = "json"# response language
# Parse paquet
try:
seps = [paquet.index(b"/")]
p_ver = paquet[:seps[0]]# protocol version
if not p_ver.decode() in PROTOCOL_VERSIONS:
client.close()
print("Error: unsupported protocol version")
sendErrorToClient(client, 17, resp_lng)# Communication error: unsupported protocol version
continue
seps.append(paquet.index(b"/", seps[0]+1))
seps.append(paquet.index(b"\n", seps[1]+1))
except ValueError:
client.close()
print("Error: decoding header")
sendErrorToClient(client, 16, resp_lng)# Communication error: decoding header
continue
p_lng = paquet[seps[0]+1:seps[1]]# data language
resp_raw = b""# raw response
resp = None# response
resp_lng = ""# response language
if p_len > 0:
p_raw = paquet[p_data_index:]
......@@ -274,27 +279,59 @@ Options:\n\
try:
p_data = json.loads(p_raw)
except json.JSONDecodeError:
client.close()
print("Error: decoding JSON")
sendErrorToClient(client, 19, resp_lng)# Communication error: decoding JSON
continue
if "query" in p_data:
p_resp = True
resp = {}
resp_lng = "json"
if "games" in p_data["query"]:
resp["games"] = []
for game in games:
if game.public:
resp["games"].append({"name":game.name, "creation_time":game.creation_time, "leader_name":game.leader_name, "n_players":len(game.players), "money_system":game.money_system.name})
gp = {"name":game.name, "creation_time":game.creation_time, "leader_name":game.leader_name, "consts":game.C, "n_players":len(game.players), "money_system":None}
if game.money_system != None:
gp["money_system"] = game.money_system.name
resp["games"].append(gp)
if "server_info" in p_data["query"]:
resp["server_info"] = {"version":VERSION, "protocol_versions":PROTOCOL_VERSIONS}
if "new_game" in p_data:
p_resp = True
g = p_data["new_game"]
g_leader_address = addr
if "leader_address" in g:
g_leader_address = [g["leader_address"], g_leader_address[1]]
if "leader_port" in g:
g_leader_address = [g_leader_address[0], g["leader_port"]]
g_leader_name = "Guru"
if "leader_name" in g:
g_leader_name = g["leader_name"]
g_consts = CONSTS.copy()
if "consts" in g:
g_consts = g["consts"]
g_public = True
if "public" in g:
g_public = g["public"]
if not "name" in g:
sendErrorToClient(client, 49, resp_lng)# Game management error: miss new game name
continue
if g["name"] in games_index:
sendErrorToClient(client, 48, resp_lng)# Game management error: that game name is already used
continue
game = Game(g["name"], g_public, g_leader_name, g_leader_address, g_consts)
games.append(game)
games_index[game.name] = game
resp["new_game_info"] = {"name":game.name, "public":game.public, "creation_time":game.creation_time, "leader_name":game.leader_name, "leader_address":game.leader_address, "consts":game.C}
else:
client.close()
print("Error: unknown language '"+str(p_lng)+"'")
sendErrorToClient(client, 18, resp_lng)# Communication error: unknown language
continue
if p_resp:
......
......@@ -6,6 +6,25 @@ PROTOCOL_VERSION = b"geco0"
PROTOCOL_LANG = b"json"
BUFFER = 1024
# Test game constants (just for testing, do not play with that values)
CONSTS = {
"N_VALUES": 5, # number of values types
"N_WVALUES": 1, # number of waiting values types
"TURN_DURATION": 600, # in seconds
"N_TURNS": 12, # number of turns in a game
"TURN_YEARS": 7, # number of years by turn
"LIFESPAN": 9, # max age
"N_DIGITS": 2, # number of decimals
"START_VALUES": 5 # number of random values for beginning
}
HOST = getargv(argv, "-h", "127.0.0.1")
try:
PORT = int(getargv(argv, "-p", "8651"))
except ValueError:
print("Error: port must be an integer")
exit(1)
if "--help" in argv:
print("\n\
PyĞeconomicus test client\n\
......@@ -15,13 +34,13 @@ Options:\n\
-p <port> Server port (default: "+str(PORT)+")\n\
--help Show this message\n\
")
exit()
HOST = getargv(argv, "-h", "127.0.0.1")
try:
PORT = int(getargv(argv, "-p", "8651"))
except ValueError:
print("Error: port must be an integer")
exit(1)
NEWGAME_DEFS = {
"1":{},# Empty, should return error 49
"2":{"name":"Test game"},# Should work once with default values, and return 48 after
"3":{"name":"Foobar", "leader_name":"John Doe", "leader_address":"testaddr", "leader_port":1234, "public":False, "consts":CONSTS}# Should set every parameter
}
server_address = (HOST, PORT)
print("Server: "+str(server_address))
......@@ -40,7 +59,8 @@ while True:
quit quit
help show help
i query=server_info
g query=games""")
g query=games
n new_game""")
continue
data = {}
......@@ -53,6 +73,11 @@ while True:
if not "query" in data:
data["query"] = []
data["query"].append("games")
if "n" in p:
for k in NEWGAME_DEFS:
if k in p:
data["new_game"] = NEWGAME_DEFS[k]
break
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_address)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment