class MySocket:
"""demonstration class only
- coded for clarity, not efficiency
"""
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def myreceive(self):
chunks = []
bytes_recd = 0
while bytes_recd < MSGLEN:
chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
if chunk == b'':
raise RuntimeError("socket connection broken")
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
return b''.join(chunks)
如果套接字^{}方法返回0,则发送循环中断。在
这段代码背后的逻辑是当send方法返回“0bytes sent”时,套接字连接的发送端应该放弃发送数据的努力。这对于^{}方法来说是肯定的,在阻塞模式下为套接字读取的零字节应该被解释为EOF,因此读取端应该放弃。在
但是我不明白在什么情况下send方法可以返回零。我对pythonsockets的理解是,send由于操作系统级别的缓冲而立即返回。如果缓冲区已满,send将阻塞,或者如果连接在远程端关闭,则引发异常。在
最后假设send返回0而不引发异常:这是否真的表示所有未来的send调用都将返回零?在
我做了一些测试(虽然在OSX上只使用了连接到::1的套接字),但是没有找到send返回0的情况。在
编辑
HOWTO声明:But if you plan to reuse your socket for further transfers, you need
to realize that there is no EOT on a socket. I repeat: if a socket
send or recv returns after handling 0 bytes, the connection has been
broken. If the connection has not been broken, you may wait on a recv
forever, because the socket will not tell you that there’s nothing
more to read (for now).
{{{3}在cda4}的任何一方都返回一个我正在寻找一个具体的例子,在这个例子中,您可以显示从send接收0表示连接断开(发送时将继续返回0)