一棵菠菜 发表于 2014-05-19 10:04

Python twisted的疑问

我最近在学习twisted但是看着官方的文档有些问题,请教下大家,下面是2个简单的实例from twisted.internet.protocol import Protocol

class Echo(Protocol):

    def dataReceived(self, data):
      self.transport.write(data)这是一个简单的消息接受的类,重写了Protocol中的dataReceived,这里我有个疑问了,我查看了源代码中的Protocol类,并未发现有write这个属性,为何这里要这样写?这样的代码运行期也是错误的,就是报错没有write属性。为什么啊。!!!!
下面的Protocol代码class BaseProtocol:
    """
    This is the abstract superclass of all protocols.

    Some methods have helpful default implementations here so that they can
    easily be shared, but otherwise the direct subclasses of this class are more
    interesting, L{Protocol} and L{ProcessProtocol}.
    """
    connected = 0
    transport = None

    def makeConnection(self, transport):
      """Make a connection to a transport and a server.

      This sets the 'transport' attribute of this Protocol, and calls the
      connectionMade() callback.
      """
      self.connected = 1
      self.transport = transport
      self.connectionMade()

    def connectionMade(self):
      """Called when a connection is made.

      This may be considered the initializer of the protocol, because
      it is called when the connection is completed.For clients,
      this is called once the connection to the server has been
      established; for servers, this is called after an accept() call
      stops blocking and a socket has been received.If you need to
      send any greeting or initial message, do it here.
      """

                                                               
connectionDone=failure.Failure(error.ConnectionDone())
connectionDone.cleanFailure()


@implementer(interfaces.IProtocol, interfaces.ILoggingContext)
class Protocol(BaseProtocol):
    """
    This is the base class for streaming connection-oriented protocols.

    If you are going to write a new connection-oriented protocol for Twisted,
    start here.Any protocol implementation, either client or server, should
    be a subclass of this class.

    The API is quite simple.Implement L{dataReceived} to handle both
    event-based and synchronous input; output can be sent through the
    'transport' attribute, which is to be an instance that implements
    L{twisted.internet.interfaces.ITransport}.Override C{connectionLost} to be
    notified when the connection ends.

    Some subclasses exist already to help you write common types of protocols:
    see the L{twisted.protocols.basic} module for a few of them.
    """

    def logPrefix(self):
      """
      Return a prefix matching the class name, to identify log messages
      related to this protocol instance.
      """
      return self.__class__.__name__

    def dataReceived(self, data):
      """Called whenever data is received.

      Use this method to translate to a higher-level message.Usually, some
      callback will be made upon the receipt of each complete protocol
      message.

      @param data: a string of indeterminate length.Please keep in mind
            that you will probably need to buffer some data, as partial
            (or multiple) protocol messages may be received!I recommend
            that unit tests for protocols call through to this method with
            differing chunk sizes, down to one byte at a time.
      """

    def connectionLost(self, reason=connectionDone):
      """Called when the connection is shut down.

      Clear any circular references here, and any external references
      to this Protocol.The connection has been closed.

      @type reason: L{twisted.python.failure.Failure}
      """

r2007 发表于 2014-05-19 10:07

这个例子不完整啊,没有协议工厂也没有reactor

一棵菠菜 发表于 2014-05-19 10:16

恩,我知道不是一个完整的例子,transport确实没有write属性,这让我很难理解。我再试试完整的例子。

一棵菠菜 发表于 2014-05-19 10:19

这个是比较完整的实例还是有不理解的地方from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class QOTD(Protocol):

    def connectionMade(self):
      # self.factory was set by the factory's default buildProtocol:
      self.transport.write(self.factory.quote + '\r\n')                      <==================真心搞不懂这里,代码如何能正确运行
      self.transport.loseConnection()


class QOTDFactory(Factory):

    # This will be used by the default buildProtocol to create new protocols:
    protocol = QOTD                   <=====================这样定义不会有错?

    def __init__(self, quote=None):
      self.quote = quote or 'An apple a day keeps the doctor away'

endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory("configurable quote"))
reactor.run()

一棵菠菜 发表于 2014-05-19 10:20

回复 2# r2007

能帮我看看吗?


   

一棵菠菜 发表于 2014-05-19 10:36

谢谢,似乎只要调用了factory上面一切错误都被纠正了。。。。。。。

r2007 发表于 2014-05-19 10:45

factory建立连接时会用protocol = QOTD这个变量值创建一个协议实例,并且将自己以及transport传给这个实例,所以协议就有了factory和transport的引用变量了。

一棵菠菜 发表于 2014-05-19 10:48

回复 7# r2007


    谢谢您的解答,我这里学习twisted比较费劲,不知道有什么好的方法学习这个框架呢?

r2007 发表于 2014-05-19 10:57

twisted官网文档,这个没办法学习曲线较陡。

一棵菠菜 发表于 2014-05-19 11:02

框架太大,很难看懂啊。。。。。。。。。各种继承,疯了都。
页: [1] 2
查看完整版本: Python twisted的疑问