简体   繁体   English

当客户端与服务器断开连接时,我可以从“try:”块中的 function 内部引发异常吗?

[英]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.我正在尝试使用 python 套接字构建一个简单的服务器-客户端聊天室。

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.其中receive_message()在其中调用client.recv(HEADER)并在没有消息时返回False ,或者在一切正常时返回{"header": msg_header, "data": msg}

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?我的问题是:如果client.recv() receive_message()内部失败,它会引发异常并打印"client disconnected"吗?

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.我定义了一个名为handle_disconnection()的 function 来处理上面代码中的except内容。

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.如果client.recv()将引发异常,您将在receive_message()内部处理它,而handle_connection()将不会收到异常。

I suggest you to identify situations when you want to control the flow with exceptions or with if-else.我建议您确定要通过异常或 if-else 控制流程的情况。 I think receive_message() should return a value of message or throw ConnectionError when there are connection issues.我认为receive_message()应该在出现连接问题时返回 message 值或抛出ConnectionError In case when there are no messages from the socket you can return None or raise NoMessagesAvailableError .如果套接字没有消息,您可以返回None或引发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.当您离开 memory 时,您的代码将打印client disconnected

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果客户端与服务器断开连接,如何断开连接? - How do I drop a connection if client disconnects from server? 我可以从pdb引发异常吗? (用于调试) - Can I raise an exception from pdb? (for debugging) 在“尝试”中的“提高”,何时以及如何使用“提高”? - 'raise' inside 'try' , when and how do I use 'raise? 如何从 python 中的“with”块中引发异常 - How to raise an exception from within an 'with' block in python 我可以编写lambda函数引发异常吗? - Can I write a lambda function to raise an exception? 当另一个客户端连接到服务器时客户端断开连接 - Client disconnects when another client connects to the server 当我从Linux机器尝试到Windows ssh客户端服务器时,来自pexpect(pxssh)的SSH失败 - SSH from pexpect (pxssh) fails when I try from a linux machine to a windows ssh client server python:如果finally块引发异常,则从try块恢复异常 - python: recover exception from try block if finally block raises exception 如何检测客户端何时断开与UDS的连接(Unix域套接字) - How to detect when a client disconnects from a UDS (Unix Domain Socket) 捕获由try-block内的函数引发的自定义异常 - Catch custom Exception that is raised by a function inside the try-block
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM