调用reactor.run(),就会调用到mainloop函数,从而调用到select或epoll,监控fd的读写。

posixbase.py:

    def listenTCP(self, port, factory, backlog=50, interface=''):
p = tcp.Port(port, factory, backlog, interface, self)
p.startListening()#会调用self.startReading(),再调用self.reactor.addReader(self)
#把自己加入epoll
return p def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
c = tcp.Connector(host, port, factory, timeout, bindAddress, self)
c.connect()
return c

factory类负责connect的管理,比如connect的建立、丢失、失败等,procotol是负责数据的接收。

 tcp.Connector(host, port, factory, timeout, bindAddress, self)

Connector类有factory,由factory可以找出procotol协议,协议主要是指tcp、process、ssl等。
class ClientCreator:
"""
Client connections that do not require a factory. The various connect* methods create a protocol instance using the given
protocol class and arguments, and connect it, returning a Deferred of the
resulting protocol instance. Useful for cases when we don't really need a factory. Mainly this
is when there is no shared state between protocol instances, and no need
to reconnect. The C{connectTCP}, C{connectUNIX}, and C{connectSSL} methods each return a
L{Deferred} which will fire with an instance of the protocol class passed to
L{ClientCreator.__init__}. These Deferred can be cancelled to abort the
connection attempt (in a very unlikely case, cancelling the Deferred may not
prevent the protocol from being instantiated and connected to a transport;
if this happens, it will be disconnected immediately afterwards and the
Deferred will still errback with L{CancelledError}).
""" def __init__(self, reactor, protocolClass, *args, **kwargs):
self.reactor = reactor
self.protocolClass = protocolClass
self.args = args
self.kwargs = kwargs def _connect(self, method, *args, **kwargs):
"""
Initiate a connection attempt. @param method: A callable which will actually start the connection
attempt. For example, C{reactor.connectTCP}. @param *args: Positional arguments to pass to C{method}, excluding the
factory. @param **kwargs: Keyword arguments to pass to C{method}. @return: A L{Deferred} which fires with an instance of the protocol
class passed to this L{ClientCreator}'s initializer or fails if the
connection cannot be set up for some reason.
"""
def cancelConnect(deferred):
connector.disconnect()
if f.pending is not None:
f.pending.cancel()
d = defer.Deferred(cancelConnect)#会生成一个延迟对象
f = _InstanceFactory(
self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
connector = method(factory=f, *args, **kwargs)
return d def connectTCP(self, host, port, timeout=30, bindAddress=None):
"""
Connect to a TCP server. The parameters are all the same as to L{IReactorTCP.connectTCP} except
that the factory parameter is omitted. @return: A L{Deferred} which fires with an instance of the protocol
class passed to this L{ClientCreator}'s initializer or fails if the
connection cannot be set up for some reason.
"""
return self._connect(
self.reactor.connectTCP, host, port, timeout=timeout,
bindAddress=bindAddress)#返回一个延迟对象
class BaseConnector:
"""Basic implementation of connector. State can be: "connecting", "connected", "disconnected"
"""
timeoutID = None
factoryStarted = 0 def __init__(self, factory, timeout, reactor):
self.state = "disconnected"
self.reactor = reactor
self.factory = factory
self.timeout = timeout def disconnect(self):
"""Disconnect whatever our state is."""
if self.state == 'connecting':
self.stopConnecting()
elif self.state == 'connected':
self.transport.loseConnection() def connect(self):
"""Start connection to remote server."""
if self.state != "disconnected":
raise RuntimeError("can't connect in this state") self.state = "connecting"
if not self.factoryStarted:
self.factory.doStart()
self.factoryStarted = 1
self.transport = transport = self._makeTransport()#创建一个client端
if self.timeout is not None:
self.timeoutID = self.reactor.callLater(self.timeout, transport.failIfNotConnected, error.TimeoutError())
self.factory.startedConnecting(self)

重要结论:调用

twisted reactor分析的更多相关文章

  1. twisted reactor 实现源码解析

    twisted reactor 实现源码解析 1.      reactor源码解析 1.1.    案例分析代码: from twisted.internet import protocol fro ...

  2. twisted reactor calllater实现

    twisted reactor calllater实现 1.      calllater实现代码 测试源码: from twisted.internet import reactor from tw ...

  3. (三)认识twisted reactor

    一.reactor是单线程模型,简单粗暴,也就是说网络IO和我们的业务逻辑一般是在一个线程里,其中网络IO通过event loop的方式去异步执行,效率也很高.看下官网的这幅图,比较清晰 twiste ...

  4. twisted reactor执行流程

    #reactorbase的主循环 def mainLoop(self): while self._started: try: while self._started: # Advance simula ...

  5. 理解twisted中的reactor和deferred(一)

    Deferred是一个延迟加载对象,这个概念类似于tornado future,是调用异步操作返回的一个对象,其中包括了操作成功后的回调处理,错误后的回调处理. 简单讲,当我们需要执行一个耗时操作,比 ...

  6. 笔记-twisted源码-import reactor解析

    笔记-twisted源码-import reactor解析 1.      twisted源码解析-1 twisted reactor实现原理: 第一步: from twisted.internet ...

  7. scrapy爬虫具体案例步骤详细分析

    scrapy爬虫具体案例详细分析 scrapy,它是一个整合了的爬虫框架, 有着非常健全的管理系统. 而且它也是分布式爬虫, 它的管理体系非常复杂. 但是特别高效.用途广泛,主要用于数据挖掘.检测以及 ...

  8. scrapy爬行乌云网公开漏洞程序的分析

    # -*- coding: utf-8 -*- from datetime import datetime import pymongo import scrapy from wooyun.items ...

  9. python网络编程——SocketServer/Twisted/paramiko模块

    在之前博客C/S架构的网络编程中,IO多路复用是将多个IO操作复用到1个服务端进程中进行处理,即无论有多少个客户端进行连接请求,服务端始终只有1个进程对客户端进行响应,这样的好处是节省了系统开销(se ...

随机推荐

  1. python函数 传参的多种方式 解读

    1.函数的参数在哪里定义 在python中定义函数的时候,函数名后面的括号里就是用来定义参数的,如果有多个参数的话,那么参数之间直接用逗号, 隔开 案列: 2.带参数的函数调用: 函数定义了参数,那么 ...

  2. 在HP-UX 11.11用swinstall安装gcc 4.2.3

    agent60 在linux上执行不了,原因是操作系统内核版本不一致,需要重新编译包. file $SHELL 显示  PA-RISC1.1 在HP-UX 11.31 PA-RISC1.1 版本中 编 ...

  3. linux上安装telnet服务

    [LINUX] 使用yum 安装.开启 telnet 服务 pasting 一.安装telnet 1.检测telnet-server的rpm包是否安装  [root@localhost ~]# rpm ...

  4. 廖雪峰Java1-3流程控制-1输入输出

    1.输入 导入java.util.Scanner 创建Scanner对象并传入System.in 使用Scanner.nextLine()读取用户输入的字符串 Scanner.nextInt()读取用 ...

  5. Recyclerview 实现上拉加载更多

    LinearLayoutManager layoutManager; layoutManager = new LinearLayoutManager(getActivity()); layoutMan ...

  6. [UE4]UMG编辑器:中心点对齐

  7. nginx 端口转发配置

    nginx.conf #user nobody; worker_processes ; #error_log logs/error.log; #error_log logs/error.log not ...

  8. CS229 3.用Normal Equation拟合Liner Regression模型

    继续考虑Liner Regression的问题,把它写成如下的矩阵形式,然后即可得到θ的Normal Equation. Normal Equation: θ=(XTX)-1XTy 当X可逆时,(XT ...

  9. 「2017 山东一轮集训 Day6」子序列(矩阵快速幂)

    /* 找出了一个dp式子 是否能够倍增优化 我推的矩阵不太一样 是 1 0 0 0 0 0 0 0 0 -1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 2 求得逆矩阵大概就是 1 0 0 ...

  10. ORACLE和MYSQL的简单区别

    1,Oracle没有offet,limit,在mysql中我们用它们来控制显示的行数,最多的是分页了.oracle要分页的话,要换成rownum. 2,oracle建表时,没有auto_increme ...