问题
I am using protocol.Protocol to receive data from a server. As follows
from twisted.internet.protocol import Protocol, Factory
class MyProtocol(Protocol):
def dataReceived(self, data):
print data
class MyFactory(Factory):
def startedConnecting(self, connector):
print 'Started to connect.'
def buildProtocol(self, addr):
print 'Connected.'
return MyProtocol()
When I receive large data, due to the TCP stream fragmentation, I only receive part of the incoming messages. I m trying to buffer the data I receive. However, I am not able to receive the remaining data. What is a good practice to receive all the data after fragmentation?
回答1:
This is a frequently asked question about Twisted. You can find the answer in the Twisted FAQ. Check out the classes that it recommends, such as Int16StringReceiver or NetstringReceiver. Or, for a full-featured inter-process messaging system, check out AMP (the Asynchronous Messaging Protocol), which also has implementations in other languages.
回答2:
The function that you want to override is stringReceived
.
When using Int16StringReceiver
, stringReceived
is entered after an entire length-prefixed string has been received, while dataReceived
may be entered zero or more times during the reception of each string.
dataReceived
is the call which the Int16StringReceiver
uses to construct the complete packet before calling stringReceived
. It might have to parse multiple strings received at the same time, or wait for a complete string to be received.
来源:https://stackoverflow.com/questions/11836855/fragmented-data-in-twisted-datarecivied