When and why socket.send() returns 0 in python?

前端 未结 2 1837
逝去的感伤
逝去的感伤 2021-02-13 14:34

The python3 socket programming howto presents this code snippet

class MySocket:
    \"\"\"demonstration class only
      - coded for clarity, not efficiency
             


        
2条回答
  •  再見小時候
    2021-02-13 15:05

    I might be wrong, but I think you are looking for an impossible situation...

    As @mementum has shown in his answer, it is theoretically possible for a socket to return zero when there is no error, but also no data sent.

    However, as shown elsewhere on SO this can only happen in very specific scenarios. In my experience (and also covered in the comments to the accepted answer) you would only ever get a zero result on a non-blocking socket when the network is congested. Now Python sockets are blocking by default, which means that the kernel should wait until there is room to take some more data then return how many bytes were queued. By definition, this can never be zero.

    So, putting it all together, since your snippet doesn't reset the socket type - e.g. using the set_blocking function - it is using blocking sockets and so cannot return zero and thus cannot hit the path mementum identified.

    This is backed up by the fact that you have been unable to trigger the specific line of code no matter what you do.

提交回复
热议问题