使用带有socket.recv_into的bytearray

cya*_*ann 14 sockets bytearray python-2.7

我正在做一些套接字IO,并使用bytearray对象作为缓冲区.我想使用csock.recv_into接收带有此偏移量的数据,如下所示,以避免创建中间字符串对象.不幸的是,似乎字节数不能以这种方式使用,并且下面的代码不起作用.

buf    = bytearray(b" " * toread)
read   = 0
while(toread):
  nbytes = csock.recv_into(buf[read:],toread)
  toread -= nbytes
  read   += nbytes
Run Code Online (Sandbox Code Playgroud)

所以不是我使用下面的代码,它不会使用一个临时的字符串(和作品)...

buf    = bytearray(b" " * toread)
read   = 0
while(toread):
  tmp = csock.recv(toread)
  nbytes = len(tmp)
  buf[read:] = tmp
  toread -= nbytes
  read   += nbytes
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方法来执行此操作,不需要复制中间字符串?

nne*_*neo 25

用a memoryview来包装你的bytearray:

buf = bytearray(toread)
view = memoryview(buf)
while toread:
    nbytes = sock.recv_into(view, toread)
    view = view[nbytes:] # slicing views is cheap
    toread -= nbytes
Run Code Online (Sandbox Code Playgroud)