Read from socket: Is it guaranteed to at least get x bytes?

前端 未结 8 1914
一生所求
一生所求 2021-01-18 18:41

I have a rare bug that seems to occur reading a socket.

It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than th

8条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-18 19:43

    Use recv_into(...) method from the socket module.

    Robert S. Barnes written the example in C.

    But you can use Python 2.x with standard python-libraries:

    def readReliably(s,n):
        buf = bytearray(n)
        view = memoryview(buf)
        sz = s.recv_into(view,n)
        return sz,buf
    
    while True:
      sk,skfrom = s.accept()
      sz,buf = io.readReliably(sk,4)
      a = struct.unpack("4B",buf)
      print repr(a)
      ...
    

    Notice, that sz returned by readReliably() function may be greater than n.

提交回复
热议问题