您的位置:首页 > 编程语言 > Python开发

[Python-Twisted] 协议基类源码分析。

2010-02-04 00:22 666 查看
学习Twisted时,有时老感觉摸不着边际,虽然说要用什么twisted都给你实现了,但心里总有不踏实之感。

遂从twisted.internet.protocol.Protocol这个所有协议的基类入手分析之。

打开twisted.internet.protocol.py

ps:学python时感觉模块和类的名称比较混乱,由上面这个twisted.internet.protocol.Protocol这个就可见一般,不过只要记住一条

[Python中类名首字母大写,模块名函数等首字母小写]那么很容易区分其中protocol是模块,Protocol中模块中的一个类。happy

twisted.internet.protocol.py这个文件很重要, 协议的基类工厂类基本都在这里。

注意:以下代码省略注释

首先看Protocol 的code:
class Protocol(BaseProtocol):

    implements(interfaces.IProtocol)

    def dataReceived(self, data):

 

    def connectionLost(self, reason=connectionDone):

    很简洁,定义了两个方法,这两个方法写过twisted的应该都见过,为什么没有实现这两个方法?,呵呵 这两个函数都是被twisted调用的,需要你自己实现。还有就是implements(interfaces.IProtocol),我也不知道这个是干嘛。姑且认为是python的 实现接口吧。

IProtocol的定义:

class IProtocol(Interface):

    def dataReceived(data):

    def connectionLost(reason):
    

    def makeConnection(transport):
       

    def connectionMade():
 什么?又没实现?接口嘛 不必惊慌。

看看BaseProtocol:

class BaseProtocol:
    """This is the abstract superclass of all protocols.

    If you are going to write a new protocol for Twisted, start here.  The
    docstrings of this class explain how you can get started.  Any protocol
    implementation, either client or server, should be a subclass of me.

    My API is quite simple.  Implement dataReceived(data) 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}.

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

    connected = 0
    transport = None

    def makeConnection(self, transport):
        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.
        """

一上就是牛逼哄哄的BaseProtocol了,是说有twisted协议的基类,代码中我们可以看到transport的初始化,还有connectionMade被twisted调用。注释很详细就不多说了。下一次结合Factory来分析下。

搞IT E文太重要了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息