简体   繁体   中英

can i raise exception from inside a function in the 'try:' block when client disconnects from the server?

im trying to build a simple server-client chatroom with python socket.

i have the following code:

def handle_connection(client):
    while(1):
        try:
            message = receive_message()
            broadcast(message["data"])
        except:     # for now i don't mind which exception
              print("client disconnected")


def receive_message(client_socket):
    try:
        message_header = client_socket.recv(HEADER)
        if len(message_header) == 0:
            return False
        message_length = int(message_header.decode("utf-8"))

        message = client_socket.recv(message_length).decode("utf-8")
        return {"header": message_header, "data": message}

    except:  # most likely will trigger when a client disconnects
        return False

where receive_message() calls inside of it to client.recv(HEADER) and returns either False when there is no message, or {"header": msg_header, "data": msg} when everything is ok.

my question is: if client.recv() fails inside of receive_message() due to the client CLI closing, will it raise the exception and print "client disconnected" , or not?

i did come up with the following solution i think works:

i defined a function called handle_disconnection() that handles all the content inside of the except in the code above.

def handle_connection(client_socket):
    while 1:
        try:
            message = receive_message()
            if not message:
                handle_disconnection(client_socket)
                break
            broadcast(message["data"])

        except:     # client disconnected
            handle_disconnection(client_socket)
            break

is this a valid and/or right programming approach to the problem? if this approach is wrong, how can i handle it correctly?

If client.recv() will raise an exception you will handle it inside of receive_message() and handle_connection() will not receive the exception.

I suggest you to identify situations when you want to control the flow with exceptions or with if-else. I think receive_message() should return a value of message or throw ConnectionError when there are connection issues. In case when there are no messages from the socket you can return None or raise NoMessagesAvailableError .

There is also a rule that tells you should catch specified exceptions, not all of them. Your code will print client disconnected when you are out of memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM