[英]Python - How to check if socket is still connected
我有以下代碼,這是不言自明的:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(host, port)
s.send("some data")
# don't close socket just yet...
# do some other stuff with the data (normal string operations)
if s.stillconnected() is true:
s.send("some more data")
if s.stillconnected() is false:
# recreate the socket and reconnect
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(host, port)
s.send("some more data")
s.close()
如何實現s.stillconnected()
我不想盲目地重新創建套接字。
如果服務器連接不再活動,調用 send 方法將拋出異常,因此您可以使用 try-exception 塊嘗試發送數據,如果拋出異常則捕獲該異常,並重新建立連接:
try:
s.send("some more data")
except:
# recreate the socket and reconnect
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(host, port)
s.send("some more data")
編輯:根據@Jean-Paul Calderone 的評論,請考慮使用sendall
方法,該方法是發送所有數據或引發錯誤的高級方法,而不是send
,后者是不保證傳輸的低級方法在所有數據中,或者使用更高級別的模塊,例如可以處理套接字生命周期的 HTTP 庫。
我用這個變體得到了很好的結果來檢查套接字是否關閉(如果你想檢查它是否仍然連接,則否定結果):
import logging
import socket
logger = logging.getLogger(__name__)
def is_socket_closed(sock: socket.socket) -> bool:
try:
# this will try to read bytes without blocking and also without removing them from buffer (peek only)
data = sock.recv(16, socket.MSG_DONTWAIT | socket.MSG_PEEK)
if len(data) == 0:
return True
except BlockingIOError:
return False # socket is open and reading from it would block
except ConnectionResetError:
return True # socket was closed for some other reason
except Exception as e:
logger.exception("unexpected exception when checking if a socket is closed")
return False
return False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.