[英]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.