python - 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.
推荐阅读
- java - Why is reading a JDBC ResultSet by position faster than by name and how much faster?
- r - Error in Running R Shiny App: Operation not allowed without an active reactive context
- react-native - 如何基于倒数计时器加速动画?
- c# - How to split an image based on transparent areas
- samba - Why an samba admin user cannot login
- rest - Postman setNextRequest 和工作流条件工作流
- express - 如何使用 Express、Express-session、Passport 和 Connect-mongo 在服务器中仅为登录用户生成会话?
- typescript - Type inference from array of elements
- javascript - 带有 localStorage 的数组不保存或被覆盖?
- matplotlib - Load Julia modules on demand