Python Twisted-指定接收到的数据中的确切字节数
我正在使用Twisted创建一个简单的TCP服务器。使用Twisted协议,是否可以指定dataReceived返回的确切字节数 我问这个问题是因为如果我可以控制传入的字节数,我可以避免处理在单个dataReceived回调中传入的部分协议消息或多个协议消息 通过在recv()方法中指定确切的字节数,我可以使用asynccore实现这一点。在Twisted中也能做到这一点将是非常棒的 谢谢Python Twisted-指定接收到的数据中的确切字节数,python,twisted,Python,Twisted,我正在使用Twisted创建一个简单的TCP服务器。使用Twisted协议,是否可以指定dataReceived返回的确切字节数 我问这个问题是因为如果我可以控制传入的字节数,我可以避免处理在单个dataReceived回调中传入的部分协议消息或多个协议消息 通过在recv()方法中指定确切的字节数,我可以使用asynccore实现这一点。在Twisted中也能做到这一点将是非常棒的 谢谢 。。。Alan为什么不定义一个缓冲区并使用它来获取您想要的大小的消息呢。LineReceiver也做了类似
。。。Alan为什么不定义一个缓冲区并使用它来获取您想要的大小的消息呢。LineReceiver也做了类似的事情 大致如下:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
class TestProtocol(Protocol):
def __init__(self):
self.__buffer = ""
self.frame_size = 3 #FRAME SIZE HERE
def connectionMade(self):
print(id(self))
self.transport.write('hello')
def connectionLost(self, reason):
print('connection lost called')
def dataReceived(self, data):
# is it possible to specify size of "data"?
print('data received called')
self.__buffer = self.__buffer+data
frame_size = self.frame_size
while len(self.__buffer) >= frame_size:
self.frame_received(self.__buffer[0:frame_size])
self.__buffer=self.__buffer[frame_size:]
def frame_received(self,data):
print data
class TestFactory(Factory):
protocol = TestProtocol
endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(TestFactory())
reactor.run()
只需处理部分协议消息 Twisted提供了许多类来帮助您实现这一点。通常,其中一个应该只适合你;必须实现自己的自定义帧协议是非常罕见的
如果您正在设计自己的协议,您可能只需要使用twisted的内置协议构建工具包。(对其他语言和框架的支持,请访问。您发布的代码不完整,因为它无法同时接收到多条消息。解析流会导致错误,最好使用类似Netty LengthFieldBasedFrameDecoder的东西。这一点很好。我认为这种情况很容易处理但是使用while循环。修改代码以使用循环处理较长的消息大小写。如果您担心bug的可能性,那么您可能希望更多地查看twisted库(或者其他人会在此处发布建议:-)),看看是否有现成的东西可以完成此工作。祝你好运。这里通常会有一段时间的循环。我以前在C++中做过很多次。然而,这个模式需要两个单元测试用例——流下溢和溢出。大多数人在第一次尝试时就弄错了,包括你的帖子。如果我能指定读取大小,我就可以避免这种模式,停止重新发明轮子。基本的软件包似乎不能满足我的需要。我正在实现一个现有的协议,它的头有点像IPv4——非常紧凑,信息量很大。
struct
模块是否足以解析其头部?
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
class TestProtocol(Protocol):
def __init__(self):
self.__buffer = ""
self.frame_size = 3 #FRAME SIZE HERE
def connectionMade(self):
print(id(self))
self.transport.write('hello')
def connectionLost(self, reason):
print('connection lost called')
def dataReceived(self, data):
# is it possible to specify size of "data"?
print('data received called')
self.__buffer = self.__buffer+data
frame_size = self.frame_size
while len(self.__buffer) >= frame_size:
self.frame_received(self.__buffer[0:frame_size])
self.__buffer=self.__buffer[frame_size:]
def frame_received(self,data):
print data
class TestFactory(Factory):
protocol = TestProtocol
endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(TestFactory())
reactor.run()