0

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()```
RobinM
  • 1
  • You don't provide any details about the crash, no stacktrace, no error message etc. I can only speculate that this crashes because of the same problem as the question I marked for duplicate. – Steffen Ullrich Jun 28 '21 at 13:50
  • Possibly you need to use `SO_REUSEADDR`: If there is a crash, it's likely a local socket is left in a `TIME_WAIT` state, so that the kernel considers that port "in use", and you will not immediately be able to re-`bind` to it. If this is the issue, it will go away on its own eventually, or you can use `setsockopt` with `SO_REUSEADDR` to override that. – Gil Hamilton Jun 28 '21 at 15:08

0 Answers0