Fix server hang

This commit is contained in:
Kayomn 2021-09-30 16:47:26 +01:00
parent f6fede5872
commit e95e2e984d
2 changed files with 9 additions and 37 deletions

View File

@ -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)

View File

@ -11,7 +11,7 @@ if (__name__ == "__main__"):
# Avoid bind() exception: OSError: [Errno 48] Address already in use # Avoid bind() exception: OSError: [Errno 48] Address already in use
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client_socket.bind((config.host, config.port)) client_socket.bind((config.host, config.port))
client_socket.listen() client_socket.listen(100)
clients = [] clients = []
@ -19,26 +19,30 @@ if (__name__ == "__main__"):
client_connection.send("Welcome to this chatroom!".encode("utf-8")) client_connection.send("Welcome to this chatroom!".encode("utf-8"))
try: try:
print("Waiting for data")
data = client_connection.recv(4096) data = client_connection.recv(4096)
print("test", data if data else "OOOPS")
while data: while data:
message = "<" + client_address[0] + "> " + data message = f"<{client_address[0]}> {data}"
print(message) print(message)
print("Propagating to clients")
for client in clients: for client in clients:
if client != client_connection: if client != client_connection:
try: try:
client.send(message) client.send(message.encode("utf-8"))
except: except:
client.close() client.close()
# if the link is broken, we remove the client # if the link is broken, we remove the client
if client_connection in clients: if client_connection in clients:
clients.remove(client_connection) clients.remove(client_connection)
print("Finished propagating")
print("Waiting for data")
data = client_connection.recv(4096) data = client_connection.recv(4096)
if client_connection in clients: if client_connection in clients: