• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python中asyncore异步模块的用法及实现httpclient的实例

Python中asyncore异步模块的用法及实现httpclient的实例

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python asyncore,异步httpclient,python httpclient,asyncore,python 异步等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

基础
这个模块是socket的异步实现,让我们先来熟悉一下模块中的一些类和方法:
1.asyncore.loop

输入一个轮询循环直到通过计数或打开的通道已关闭。

2.asyncore.dispatcher

dispatcher类是一个底层socket类的包装对象。要使它更有用, 它有一部分事件处理方法被异步循环调用。否则它就是一个标准的非阻塞socket对象。
底层的事件在特定事件或特定的连接状态告诉异步循环,某些高级事件发生了。例如, 我们要求一个socket连接到另一个主机。

(1)handle_connect() 第一次读或写事件。
(2)handle_close() 读事件没有数据可用。
(3)handle_accept 读事件监听一个socket。
(4)handle_read

在异步循环察觉到通道呼叫read()时调用。

(5)handle_write

在异步循环检测到一个可写的socket可以写的时候调用。这种方法经常实现缓冲性能。比如

def handle_write(self):
  sent = self.send(self.buffer)
  self.buffer = self.buffer[sent:]
</div>

(6)handle_expt

当有(OOB)数据套接字连接。这几乎永远不会发生,因为OOB精细地支持和很少使用。

(7)handle_connect

当socket创建一个连接时调用。

(8)handle_close

当socket连接关闭时调用。

(9)handle_error

当引发一个异常并没有其他处理时调用。

(10)handle_accept

当本地监听通道与远程端建立连接(被动连接)时调用。

(11)readable

每次在异步循环确定是否添加一个通道socket到读事件列表时调用,默认都为True。

(12)writable

每次在异步循环确定是否添加一个通道socket到写事件列表时调用, 默认为True。

(13)create_socket

与创建标准socket的时候相同。

(14)connect

与标准socket的端口设置是相同, 接受一个元组第一个参数为主机地址,第二个参数是端口号。

(15)send

向远程端socket发送数据。

(16)recv

从远程端socket读取最多buffer_size的数据。一个空的字符串意味着从另一端通道已关闭。

(17)listen

监听socket连接。

(18)bind

将socket绑定到地址。

(19)accept

接受一个连接, 必须绑定到一个socket和监听地址。

(20)close

关闭socket。

3.asyncore.dispatcher_with_send

dispatcher子类添加了简单的缓冲输出功能用于简单的客户,更复杂的使用asynchat.async_chat。

4.asyncore.file_dispatcher

file_dispatcher需要一个文件描述符或文件对象地图以及一个可选的参数,包装,使用调查()或循环()函数。如果提供一个文件对象或任何fileno()方法,该方法将调用和传递到file_wrapper构造函数。可用性:UNIX。

5.asyncore.file_wrapper

file_wrapper需要一个整数文件描述符并调用os.dup()复制处理,这样原来的处理可能是独立于file_wrapper关闭。这个类实现足够的方法来模拟一个套接字使用file_dispatcher类。可用性:UNIX。

asyncore 实例

1.一个http client的实现。

import socket
import asyncore

class Client(asyncore.dispatcher):
  
  def __init__(self, host, path):
    asyncore.dispatcher.__init__(self)
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    self.connect((host, 80))
    self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % path

  def handle_connect(self):
    pass

  def handle_close(self):
    self.close()

  def handle_read(self):
    print self.recv(8192)

  def writable(self):
    return (len(self.buffer) > 0)

  def handle_write(self):
    sent = self.send(self.buffer)
    self.buffer = self.buffer[sent:]

client = Client('www.python.org', '/')
asyncore.loop()

</div>

服务器接受连接和分配任务

import socket
import asyncore

class EchoHandler(asyncore.dispatcher_with_send):
  
  def handle_read(self):
    data = self.recv(8192)
    if data:
      self.send(data)


class EchoServer(asyncore.dispatcher):
  
  def __init__(self, host, port):
    asyncore.dispatcher.__init__(self)
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    self.set_reuse_add()
    self.bind((host, port))
    self.listen(5)

  def handle_accept(self):
    pair = self.accept()
    if pair is not None:
      sock, addr = pair
      print 'Incoming connection from %s' % repr(addr)
      handler = EchoHandler(sock)

server = EchoServer('localhost', 8080)
asyncore.loop()

</div>

2.利用asyncore的端口映射(端口转发)

import socket,asyncore

class forwarder(asyncore.dispatcher):
  def __init__(self, ip, port, remoteip,remoteport,backlog=5):
    asyncore.dispatcher.__init__(self)
    self.remoteip=remoteip
    self.remoteport=remoteport
    self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
    self.set_reuse_addr()
    self.bind((ip,port))
    self.listen(backlog)

  def handle_accept(self):
    conn, addr = self.accept()
    # print '--- Connect --- '
    sender(receiver(conn),self.remoteip,self.remoteport)

class receiver(asyncore.dispatcher):
  def __init__(self,conn):
    asyncore.dispatcher.__init__(self,conn)
    self.from_remote_buffer=''
    self.to_remote_buffer=''
    self.sender=None

  def handle_connect(self):
    pass

  def handle_read(self):
    read = self.recv(4096)
    # print '%04i -->'%len(read)
    self.from_remote_buffer += read

  def writable(self):
    return (len(self.to_remote_buffer) > 0)

  def handle_write(self):
    sent = self.send(self.to_remote_buffer)
    # print '%04i <--'%sent
    self.to_remote_buffer = self.to_remote_buffer[sent:]

  def handle_close(self):
    self.close()
    if self.sender:
      self.sender.close()

class sender(asyncore.dispatcher):
  def __init__(self, receiver, remoteaddr,remoteport):
    asyncore.dispatcher.__init__(self)
    self.receiver=receiver
    receiver.sender=self
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    self.connect((remoteaddr, remoteport))

  def handle_connect(self):
    pass

  def handle_read(self):
    read = self.recv(4096)
    # print '<-- %04i'%len(read)
    self.receiver.to_remote_buffer += read

  def writable(self):
    return (len(self.receiver.from_remote_buffer) > 0)

  def handle_write(self):
    sent = self.send(self.receiver.from_remote_buffer)
    # print '--> %04i'%sent
    self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:]

  def handle_close(self):
    self.close()
    self.receiver.close()

if __name__=='__main__':
  import optparse
  parser = optparse.OptionParser()

  parser.add_option(
    '-l','--local-ip',
    dest='local_ip',default='127.0.0.1',
    help='Local IP address to bind to')
  parser.add_option(
    '-p','--local-port',
    type='int',dest='local_port',default=80,
    help='Local port to bind to')
  parser.add_option(
    '-r','--remote-ip',dest='remote_ip',
    help='Local IP address to bind to')
  parser.add_option(
    '-P','--remote-port',
    type='int',dest='remote_port',default=80,
    help='Remote port to bind to')
  options, args = parser.parse_args()

  forwarder(options.local_ip,options.local_port,options.remote_ip,options.remote_port)
  asyncore.loop()
</div>

</div>

您可能想查找下面的文章:

  • Python中asyncore异步模块的用法及实现httpclient的实例
  • Python的Asyncore异步Socket模块及实现端口转发的例子

相关文章

  • python实现定时播放mp3
  • python中随机函数random用法实例
  • 详解Python中映射类型(字典)操作符的概念和使用
  • Python数据类型详解(一)字符串
  • 详解Python中的array数组模块相关使用
  • python简单获取数组元素个数的方法
  • Python中遇到的小问题及解决方法汇总
  • python去掉行尾的换行符方法
  • 详解Python Socket网络编程
  • Python判断操作系统类型代码分享

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python简单获取自身外网IP的方法
    • python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享
    • 浅谈Python单向链表的实现
    • Python实现信用卡系统(支持购物、转账、存取钱)
    • 举例详解Python中循环语句的嵌套使用
    • python正则表达式去掉数字中的逗号(python正则匹配逗号)
    • python中字符串类型json操作的注意事项
    • Python开发之快速搭建自动回复微信公众号功能
    • Python获取Linux系统下的本机IP地址代码分享
    • SQLite3中文编码 Python的实现

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有