From 09958314bba592570a4d4b4dff44b28cee3257e6 Mon Sep 17 00:00:00 2001 From: Vincent Le Gallic Date: Sun, 8 Feb 2015 21:03:28 +0100 Subject: [PATCH] =?utf8?q?M=C3=A0j=20protocole=20client/serveur?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- client.py | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/client.py b/client.py index 297e76d..610d123 100755 --- a/client.py +++ b/client.py @@ -19,22 +19,26 @@ from pprint import pprint sys.path.append(client_config.rsa_path) import monRSA -class DeadServer(Exception): - pass - -def full_read(sock): - """Lit sur la socket jusqu'à ce que l'output soit déJSON-izable""" - output="" - i = 0 - while True: - output+=sock.read() - i += 1 - try: - return json.loads(output) - except: - pass - if i==10 and output=="": - raise DeadServer +def full_read(socket): + """Lit un message complet sur la socket.""" + # On récupère d'abord la taille du message + length_str = '' + char = socket.recv(1) + while char != '\n': + length_str += char + char = socket.recv(1) + total = int(length_str) + # On utilise une memoryview pour recevoir les données chunk par chunk efficacement + view = memoryview(bytearray(total)) + next_offset = 0 + while total - next_offset > 0: + recv_size = socket.recv_into(view[next_offset:], total - next_offset) + next_offset += recv_size + try: + msg = json.loads(view.tobytes()) + except (TypeError, ValueError) as e: + raise NKNotJson("L'objet reçu n'est pas un JSON") + return msg def connect(sock,where,port=None): if port==None: @@ -92,8 +96,6 @@ def lit(socket): return obj["msg"] except ssl.SSLError: print "Rien à lire" - except DeadServer: - print "Serveur down ?" if __name__=="__main__": where=raw_input("quel serveur ?") -- 2.39.2