根据Twisted Documentation,方法中的data
参数不是无限的,它是:dataRecived
“一个不确定长度的字符串。请记住,您可能需要缓冲一些数据,因为可能会收到部分(或多个)协议消息!”。
所以我们需要dataRecived
手动重写方法来缓冲数据。或者使用一些从 protcol.Protocol 定义的继承类,例如:LineReceiver 类或NetstringReceiver 类来解决这个问题。
例如类的dataReceived
来源LineRecevier
如下:
def dataReceived(self, data):
"""Protocol.dataReceived.
Translates bytes into lines, and calls lineReceived (or
rawDataReceived, depending on mode.)
"""
self.__buffer = self.__buffer+data
while self.line_mode and not self.paused:
try:
line, self.__buffer = self.__buffer.split(self.delimiter, 1)
except ValueError:
if len(self.__buffer) > self.MAX_LENGTH:
line, self.__buffer = self.__buffer, ''
return self.lineLengthExceeded(line)
break
else:
linelength = len(line)
if linelength > self.MAX_LENGTH:
exceeded = line + self.__buffer
self.__buffer = ''
return self.lineLengthExceeded(exceeded)
why = self.lineReceived(line)
if why or self.transport and self.transport.disconnecting:
return why
else:
if not self.paused:
data=self.__buffer
self.__buffer=''
if data:
return self.rawDataReceived(data)