From e95e2e984dc939a9fdcc487b158c7dee08581b4b Mon Sep 17 00:00:00 2001 From: Kayomn Date: Thu, 30 Sep 2021 16:47:26 +0100 Subject: [PATCH] Fix server hang --- message.py | 32 -------------------------------- server.py | 14 +++++++++----- 2 files changed, 9 insertions(+), 37 deletions(-) delete mode 100644 message.py diff --git a/message.py b/message.py deleted file mode 100644 index e50942a..0000000 --- a/message.py +++ /dev/null @@ -1,32 +0,0 @@ -import sys -import json -import struct - - -class Message: - def __init__(self, author: str, body: str) -> None: - self.author = author - self.body = body - - def serialize(self) -> bytes: - return serialize(self.author, self.body) - - -def deserialize(data: bytes) -> Message: - buffer_length = 2 - header_length = struct.unpack(">H", data[:buffer_length])[0] - header = json.loads(data[buffer_length:header_length]) - - return Message(header["author"], header["encoded-body"]) - - -def serialize(author: str, body: str) -> bytes: - encoding = sys.getdefaultencoding() - - header_bytes = json.dumps({ - "byteorder": sys.byteorder, - "author": author, - "body": encoding, - }).encode("utf-8") - - return (struct.pack(">H", len(header_bytes)) + header_bytes) \ No newline at end of file diff --git a/server.py b/server.py index f763a81..095d0e6 100644 --- a/server.py +++ b/server.py @@ -11,7 +11,7 @@ if (__name__ == "__main__"): # Avoid bind() exception: OSError: [Errno 48] Address already in use client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) client_socket.bind((config.host, config.port)) - client_socket.listen() + client_socket.listen(100) clients = [] @@ -19,26 +19,30 @@ if (__name__ == "__main__"): client_connection.send("Welcome to this chatroom!".encode("utf-8")) try: + print("Waiting for data") data = client_connection.recv(4096) - print("test", data if data else "OOOPS") - while data: - message = "<" + client_address[0] + "> " + data + message = f"<{client_address[0]}> {data}" print(message) + print("Propagating to clients") for client in clients: if client != client_connection: try: - client.send(message) + client.send(message.encode("utf-8")) except: client.close() + # if the link is broken, we remove the client if client_connection in clients: clients.remove(client_connection) + print("Finished propagating") + + print("Waiting for data") data = client_connection.recv(4096) if client_connection in clients: