我正在尝试通过一个套接字接收一系列的原型;我不会预先知道数据的数量。我发送了相当数量的邮件,并在接收到它们时需要缓冲消息 (以确保收到所有消息)。我想利用Python中可用的bytearray/memoryview来消除不必要的副本。
我目前正在使用一个字符串,并在接收到数据时追加数据。这很容易,我可以通过这样的操作来“转移”“缓冲区”:
# Create the buffer
str_buffer = []
# Get some data and add it to our "buffer"
str_buffer += "Hello World"
# Do something with the data . . .
# "shift"/offset the message by the data we processed
str_buffer = str_buffer[6:]是否可以使用字节数组/内存视图进行类似的操作?
# Create the buffer/memoryarray 
buffer = bytearray(1024)
view   = memoryview(buffer)
# I can set a single byte
view[0] = 'a'
# I can "offset" the view by the data we processed, but doing this 
# shrinks the view by 3 bytes. Doing this multiple times eventually shrinks
# the view to 0.
view = view[3:]当我试图将更多的数据添加到末尾时,问题就出现了。如果我曾经“抵消”现有视图,视图的大小“缩小*”,我可以添加越来越少的数据。是否存在重用现有内存视图并将数据移至左侧的问题?
*根据文档,我知道我不能调整数组的大小。我认为缩小的错觉是我的误解。
发布于 2014-04-03 05:04:29
你真的,老实说,不需要事先知道需要多少数据,只要一直读下去,直到你没有更多的数据:
import socket, sys
HOST = 'localhost'        # The remote host
PORT = 50007              # The same port as used by the server
recvbuff = bytearray(16)
recvview = memoryview(recvbuff)
size = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
    nbytes = s.recv_into(recvview)
    if not nbytes:
        break
    size += nbytes
    recvview = recvview[nbytes:]
    if not len(recvview):
        print "filled a chunk", recvbuff
        recvview = memoryview(recvbuff)
print 'end of data', recvbuff[:len(recvview)], size
s.close()https://stackoverflow.com/questions/22827794
复制相似问题