python中send_何时何地套接字.send()在python中返回0?

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值