我正在尝试学习 python 扭曲的互联网框架,但有一件事让我感到困惑。使用 telnet 进行的初始测试表明,每当接收数据时都会调用 protocol.Protocol.dataReceived()
方法。因此,如果我将其定义如下,它将在触发之前等待 EOL:
def dataReceived(self, data):
print "MyProtocol::dataReceived, (%s)" %(data)
输出:
MyProtocol::dataReceived, (dgdfg
)
但是,一旦我添加额外的一行:
def dataReceived(self, data):
print "MyProtocol::dataReceived, (%s)" %(data)
self.transport.write(data)
它会为每个角色触发。
输出:
MyProtocol::dataReceived, (d)
MyProtocol::dataReceived, (g)
MyProtocol::dataReceived, (d)
MyProtocol::dataReceived, (f)
MyProtocol::dataReceived, (g)
MyProtocol::dataReceived, (
)
对这里发生的事情有什么想法吗?
工厂是protocol.Factory
,协议(protocol)是protocol.Protocol
谢谢
最佳答案
在 dataReceived
触发 ( docs ) 之前不会发生行缓冲,因此不能保证您收到的内容是 EOL 分隔的。但这不太可能是问题的根源,因为您发送的消息适合默认的读取 block 大小。您能分享一下您的其余代码吗?
您可以查看一个 LineReceiver
协议(protocol) ( docs ),它会为您处理行缓冲。这是一个例子:
from twisted.internet import reactor
from twisted.protocols import basic
class EchoLine(basic.LineReceiver):
delimiter = '\n' # default is '\r\n'
def lineReceived(self, line):
print("received: %s" % line)
self.sendLine(line)
class EchoFactory(protocol.ServerFactory):
protocol = EchoLine
reactor.listenTCP(port, EchoFactory())
reactor.run()
关于python - dataReceived() 方法在 python 扭曲框架中混淆行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659603/