Twisted - 指定dataReceived中的确切字节数

时间:2014-01-17 21:39:59

标签: python twisted

我使用Twisted来创建一个简单的TCP服务器。使用Twisted协议,是否可以确定 dataReceived 返回的确切字节数?

from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class TestProtocol(Protocol):

    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')

class TestFactory(Factory):
    protocol = TestProtocol

endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(TestFactory())
reactor.run()

我问这个问题,因为如果我可以控制进入的字节数,我可以避免处理单个dataReceived回调中的部分协议消息或多个协议消息。

我能够通过指定recv()方法中的确切字节数来使用asynccore实现此目的。能够在Twisted中执行此操作会很棒。

由于

......艾伦

2 个答案:

答案 0 :(得分:0)

为什么不定义缓冲区并使用它来获取所需大小的消息。 LineReciever做了类似的事情。

有些事情:

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()

答案 1 :(得分:0)

只需处理部分协议消息。

Twisted提供了许多课程来帮助您完成此项工作in the twisted.protocols.basic package。通常其中一个应该适合你;必须实现自己的自定义框架协议是非常不寻常的。

如果您正在设计自己的协议,则应该使用twisted的内置协议构建工具包Asynchronous Messaging Protocol。 (支持amp-protocol.net提供的其他语言和框架。