Fix server hang
This commit is contained in:
parent
f6fede5872
commit
e95e2e984d
32
message.py
32
message.py
|
@ -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)
|
14
server.py
14
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:
|
||||
|
|
Loading…
Reference in New Issue