AK_*_*AK_ 7 python sockets networking tcp tcpclient
我有以下代码,这是不言自明的:
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()
Run Code Online (Sandbox Code Playgroud)
如何实现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")
Run Code Online (Sandbox Code Playgroud)
编辑:根据@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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
31837 次 |
最近记录: |