twisted reactor分析
调用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分析的更多相关文章
- twisted reactor 实现源码解析
twisted reactor 实现源码解析 1. reactor源码解析 1.1. 案例分析代码: from twisted.internet import protocol fro ...
- twisted reactor calllater实现
twisted reactor calllater实现 1. calllater实现代码 测试源码: from twisted.internet import reactor from tw ...
- (三)认识twisted reactor
一.reactor是单线程模型,简单粗暴,也就是说网络IO和我们的业务逻辑一般是在一个线程里,其中网络IO通过event loop的方式去异步执行,效率也很高.看下官网的这幅图,比较清晰 twiste ...
- twisted reactor执行流程
#reactorbase的主循环 def mainLoop(self): while self._started: try: while self._started: # Advance simula ...
- 理解twisted中的reactor和deferred(一)
Deferred是一个延迟加载对象,这个概念类似于tornado future,是调用异步操作返回的一个对象,其中包括了操作成功后的回调处理,错误后的回调处理. 简单讲,当我们需要执行一个耗时操作,比 ...
- 笔记-twisted源码-import reactor解析
笔记-twisted源码-import reactor解析 1. twisted源码解析-1 twisted reactor实现原理: 第一步: from twisted.internet ...
- scrapy爬虫具体案例步骤详细分析
scrapy爬虫具体案例详细分析 scrapy,它是一个整合了的爬虫框架, 有着非常健全的管理系统. 而且它也是分布式爬虫, 它的管理体系非常复杂. 但是特别高效.用途广泛,主要用于数据挖掘.检测以及 ...
- scrapy爬行乌云网公开漏洞程序的分析
# -*- coding: utf-8 -*- from datetime import datetime import pymongo import scrapy from wooyun.items ...
- python网络编程——SocketServer/Twisted/paramiko模块
在之前博客C/S架构的网络编程中,IO多路复用是将多个IO操作复用到1个服务端进程中进行处理,即无论有多少个客户端进行连接请求,服务端始终只有1个进程对客户端进行响应,这样的好处是节省了系统开销(se ...
随机推荐
- 代码从Polyline读取到的坐标和属性对话框显示的不一样?
属性窗口中查询的第一个点坐标: 程序输出的各个点坐标: 差这么多? 原来是坐标系的问题,程序查询到的是世界坐标,属性窗口中是当前ucs坐标 Document doc = Application.Doc ...
- IIS短文件名泄露漏洞检测
http://www.xxxx.com/*~1****/a.aspx http://www.xxxx.com/l1j1e*~1****/a.aspx If the first one return a ...
- Ubuntu(虚拟机)下安装Qt5.5.1
1.到官网下载需要的相应版本 http://download.qt.io/archive/qt/ (这里我选择的是 qt-opensource-linux-x64-android-5.5.1.run) ...
- js实现照片墙效果
本次要实现的是一个照片墙的效果,如下图,很多图片随机的摆放在窗口中,当点击到某一张的时候,该张图片出现出现在窗口的水平垂直居中的位置. 首先,我们需要简单的结构处理图片,为了方便操作,引用了一个js库 ...
- Ubuntu 16.04安装Pycharm2017.1.1
安装pycharm 1.到官网下载安装包. 2.到下载目录下进行解压. 3.运行解压后的文件夹中的bin目录下的pycharm.sh文件. cd pycharm-community-2017.1.1/ ...
- centos6.5网络虚拟化技术
一.配置KVM虚拟机NAT网络 1.创建脚本执行权限 下面是NAT启动脚本 # vi /etc/qemu-ifup-NAT 赋予权限 # chmod +x /etc/qemu-ifup-NAT 下载镜 ...
- android-sdk和api版本
Platform Version API Level VERSION_CODE Notes Android 8.1 27 O_MR1 平台亮点Android 8.0 26 O 平台亮点An ...
- AMQP & JMS对比(转载)
AMQP & JMS对比 原文地址:https://blog.csdn.net/hpttlook/article/details/23391967 初次接触消息队列时,在网上搜索,总是会提到如 ...
- window.open 子窗口关闭刷新父页面
function JsMod(htmlurl,tmpWidth,tmpHeight){ htmlurl=getRandomUrl(htmlurl); var winObj = window.open( ...
- MFC+mongodb+nodejs 数据库的读取与写入操作
首先通过nodejs和mongodb建立后端服务器 一.在windows平台下启动mongodb服务器 1.进入mongodb的安装目录,并进去bin目录启动mongod 2.在d盘建立mongodb ...