Python 使用twisted控制传入字节的馈送
我需要解决以下问题 作为连接到服务器的客户端,服务器以以下形式发送数据块: [4字节][msg-字节块大小为Int4字节] 当使用twisted时,我需要使dataReceivedself,即使用msg部分调用的数据,我不介意接收4字节前缀,但我需要确保我在一个片段中获得整个消息块,而不是碎片,一次一个Python 使用twisted控制传入字节的馈送,python,twisted,Python,Twisted,我需要解决以下问题 作为连接到服务器的客户端,服务器以以下形式发送数据块: [4字节][msg-字节块大小为Int4字节] 当使用twisted时,我需要使dataReceivedself,即使用msg部分调用的数据,我不介意接收4字节前缀,但我需要确保我在一个片段中获得整个消息块,而不是碎片,一次一个 请告知 我最后编写了以下自定义接收器 HEADER_LENGTH = 4 class CustomReceiver(Protocol): _buffer = b'' def data
请告知 我最后编写了以下自定义接收器
HEADER_LENGTH = 4
class CustomReceiver(Protocol):
_buffer = b''
def dataReceived(self, data):
logger.info(f'DATA RECEIVED: {data}')
data = (self._buffer + data)
header = data[:HEADER_LENGTH]
logger.info(f'header: {header} len: {len(header)}')
while len(header) == HEADER_LENGTH:
response_length = int.from_bytes(header, byteorder='big')
response = data[HEADER_LENGTH:][:response_length]
self.responseReceived(response)
data = data[HEADER_LENGTH + response_length:]
header = data[:HEADER_LENGTH]
self._buffer = header
我不确定是否应该为dataReceived添加锁定机制,同时调用会损坏缓冲区数据。StatefulProtocol对这样的协议很有帮助
from twisted.protocols.stateful import StatefulProtocol
HEADER_LENGTH = 4
class YourProtocol(StatefulProtocol):
# Define the first handler and what data it expects.
def getInitialState(self):
return (
# The first handler is self._header
self._header,
# And it expects HEADER_LENGTH (4) bytes
HEADER_LENGTH,
)
# When HEADER_LENGTH bytes have been received, this is called.
def _header(self, data):
# It returns a tuple representing the next state handler.
return (
# The next thing we can handle is a response
self._response,
# And the response is made up of this many bytes.
int.from_bytes(header, byteorder='big'),
)
# When the number of bytes from the header has been received,
# this is called.
def _response(self, data):
# Application dispatch of the data
self.responseReceived(data)
# Return to the initial state to process the next received data.
return self.getInitialState()
你有一些到目前为止你尝试过的例子吗?现在回答你的问题有点困难。根据我从文档中收集的信息,我需要实现一个自定义接收器。。。听起来不错吧?