python: how to detect client disconnection on the server side?

只谈情不闲聊 提交于 2019-12-07 22:34:51

问题


I am working on socket programming in python and I want to detect client socket disconnection on server side.

Client:

socket.connect(host, port)
try:
    """ send something to server and get response from the server"""
except KeyboardInterrupt:
    socket.shutdown(socket.SHUT_RDWR)
    socket.close()

Server:

conn, address = socket.accept()
try:
    conn.send(message)
except:
    print "-1"

But when I first run this code, I close the client by keyboard interrupt and the server won't print -1 in the screen. When I try it again, the server will catch the exception and print -1.

I wonder if there is something wrong with my code. Why the server won't detect the disconnection at the first time?

Thanks.

来源:https://stackoverflow.com/questions/48756397/python-how-to-detect-client-disconnection-on-the-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!