Currently when i disconnect my client socket, the socket on the server displays an error and stops working. I implemented a method to close the connection but this only works if I send a disconnect message. If by accident the socket disconnects or crashes the disconnect message will not be send and the server socket will crash. When I try to reconnect nothing will happen and i need to reboot my server. The problem is that i need to find a solution where i dont need to reboot the server beceause rebooting is bringing further compilactions with it, hence I'm looking for a way where i can restart the socket without rebooting the entire server. At the moment the socket is started by a crontab on server start.
from sys import prefix
from threading import Thread
def accept_incoming_connections():
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("you have been connected", "utf8"))
#Saves all the client addresses to a list, and sends everything back
addresses[client] = client_address
global clientID
Thread(target=handle_client, args=(client,)).start()
def handle_client(client):
name = client.recv(BUFSIZE).decode("utf8")
clients[client] = name
while True:
msg = client.recv(BUFSIZE)
if msg != bytes("{quit}", "utf8"):
prefix = name + ": "
broadcast(msg, prefix)
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
break
def broadcast(msg, prefix=""):
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
addresses = {}
clients = {}
HOST = ' "here comes the server IP" '
PORT = "port"
BUFSIZE = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()```