using bytearray with socket.recv_into

2020-05-26 09:35发布

问题:

I am doing some socket IO, and using a bytearray object as a buffer. I would like to receive data with an offset into this buffer using csock.recv_into as shown below in order to avoid creating intermediary string objects. Unfortunately, it seems bytearrays can't be used this way, and the code below doesn't work.

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

So instead I am using the code below, which does use a temporary string (and works)...

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

Is there a more elegant way to do this that doesn't require copying intermediate strings around?

回答1:

Use a memoryview to wrap your bytearray:

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