python asyncore

原文地址:http://effbot.org/librarybook/asyncore.htm

The asyncore module

This module provides a “reactive” socket implementation. Instead of creating socket objects, and calling methods on them to do things, this module lets you write code that is called when something can be done. To implement an asynchronous socket handler, subclass the dispatcher class, and override one or more of the following methods:

  • writable is called by the asyncore framework to check if the dispatcher has data to send. The default implementation always returns True.
  • readable is called to check if the dispatcher is ready to process incoming data, if any. The default implementation always returns True.
  • handle_connect is called when a connection is successfully established.
  • handle_expt is called when a connection fails (Windows), or when out-of-band data arrives (Unix).
  • handle_accept is called when a connection request is made to a listening socket. The callback should call the accept method to get the client socket. In most cases, the callback should create another socket handler to handle the actual communication.
  • handle_read is called when there is data waiting to be read from the socket. The callback should call the recv method to get the data.
  • handle_write is called when data can be written to the socket. Use thesend method to write data.
  • handle_close is called when the socket is closed or reset.
  • handle_error(type, value, traceback) is called if a Python error occurs in any of the other callbacks. The default implementation prints an abbreviated traceback to sys.stdout.

The first example shows a time client, similar to the one for the socket module:

Example: Using the asyncore module to get the time from a time server

# File: asyncore-example-1.py

import asyncore
import socket, time

# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00

class TimeRequest(asyncore.dispatcher):
    # time requestor (as defined in RFC 868)

    def __init__(self, host, port=37):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))

    def writable(self):
        return 0 # don‘t have anything to write

    def handle_connect(self):
        pass # connection succeeded

    def handle_expt(self):
        self.close() # connection failed, shutdown

    def handle_read(self):
        # get local time
        here = int(time.time()) + TIME1970

        # get and unpack server time
        s = self.recv(4)
        there = ord(s[3]) + (ord(s[2])<<8) + (ord(s[1])<<16) + (ord(s[0])<<24L)

        self.adjust_time(int(here - there))

        self.handle_close() # we don‘t expect more data

    def handle_close(self):
        self.close()

    def adjust_time(self, delta):
        # override this method!
        print "time difference is", delta

#
# try it out

request = TimeRequest("www.python.org")

asyncore.loop()
log: adding channel <TimeRequest  at 8cbe90>
time difference is 28
log: closing channel 192:<TimeRequest connected at 8cbe90>

If you don’t want the log messages, override the log method in your dispatchersubclass.

Here’s the corresponding time server. Note that it uses two dispatchersubclasses, one for the listening socket, and one for the client channel.

Example: Using the asyncore module to implement a time server

# File: asyncore-example-2.py

import asyncore
import socket, time

# reference time
TIME1970 = 2208988800L

class TimeChannel(asyncore.dispatcher):

    def handle_write(self):
        t = int(time.time()) + TIME1970
        t = chr(t>>24&255) + chr(t>>16&255) + chr(t>>8&255) + chr(t&255)
        self.send(t)
        self.close()

class TimeServer(asyncore.dispatcher):

    def __init__(self, port=37):
        asyncore.dispatcher.__init__(self)
        self.port = port
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(("", port))
        self.listen(5)
        print "listening on port", self.port

    def handle_accept(self):
        channel, addr = self.accept()
        TimeChannel(channel)

server = TimeServer(8037)
asyncore.loop()
log: adding channel <TimeServer  at 8cb940>
listening on port 8037
log: adding channel <TimeChannel  at 8b2fd0>
log: closing channel 52:<TimeChannel connected at 8b2fd0>

In addition to the plain dispatcher, this module also includes adispatcher_with_send class. This class allows you send larger amounts of data, without clogging up the network transport buffers.

The following module defines an AsyncHTTP class based on thedispatcher_with_send class. When you create an instance of this class, it issues an HTTP GET request, and sends the incoming data to a “consumer”target object.

时间: 2024-08-08 01:28:40

python asyncore的相关文章

python Asyncore.dispatcher 理解

1.Asyncore是python的标准库.Asyncore.dispatcher 是这个库中的一个socket的框架,为socket添加了一些通用的回调方法,比如: def listen(self, num): def bind(self, addr): def connect(self, address): def accept(self): def send(self, data): def recv(self, buffer_size): def close(self): def han

Python asyncore模块

asyncore库是python的一个标准库,它是一个异步socket的包装.我们操作网络的时候可以直接使用socket等底层的库,但是asyncore使得我们可以更加方便的操作网络,避免直接使用socket,select,poll等工具时需要面对的复杂. 这个库很简单,包含了一个函数和一个类: * loop()函数* dispatcher基类 需要注意的是,loop函数是全局的,不是dispatcher的方法 每一个从dispatcher继承的类的对象,都可以看作我们需要处理的一个socket

python异步socket编程之二

三.异步client与异步server的通信 1. 服务端代码 pythone socket的server段,开放三个端口:10000,10001,10002. 例子中是每个server绑定一个端口,测试的时候需要分别开3个shell,分别运行. 这太麻烦了,就分别用三个Thread来运行这些services #!/usr/bin/env python # # -*- coding:utf-8 -*- # File: multithrd_socket_server.py # import opt

Python异步通信模块asyncore

Python异步通信模块asyncore 介绍 Python的asyncore模块提供了以异步的方式写入套接字服务的client和server的基础结构. 模块主要包含: asyncore.loop(-) - 用于循环监听网络事件.loop()函数负责检測一个字典.字典中保存dispatcher的实例. asyncore.dispatcher类 - 一个底层套接字对象的简单封装.这个类有少数由异步循环调用的,用来事件处理的函数. dispatcher类中的writable()和readable(

python通过protobuf实现rpc

由于项目组现在用的rpc是基于google protobuf rpc协议实现的,所以花了点时间了解下protobuf rpc.rpc对于做分布式系统的人来说肯定不陌生,对于rpc不了解的童鞋可以自行google,这里只是做个简单的介绍.rpc的主要功能是让分布式系统的实现更为简单,为提供强大的远程调用而不损失本地调用语义的简洁性.为了实现这个目标,rpc框架需要提供一种透明调用机制让使用者不必显示区分本地调用还是远程调用.rpc架构涉及的组件如下: 客户方像调用本地方法一样去调用远程接口方法,R

Python著名的lib和开发框架(均为转载)

第一,https://github.com/vinta/awesome-python Awesome Python A curated list of awesome Python frameworks, libraries, software and resources. Inspired by awesome-php. Awesome Python Admin Panels Algorithms and Design Patterns Anti-spam Asset Management A

Python 3.x标准模块库目录

出处:http://blog.csdn.net/sadfishsc/article/details/10390065 文本 1. string:通用字符串操作 2. re:正则表达式操作 3. difflib:差异计算工具 4. textwrap:文本填充 5. unicodedata:Unicode字符数据库 6. stringprep:互联网字符串准备工具 7. readline:GNU按行读取接口 8. rlcompleter:GNU按行读取的实现函数 二进制数据 9. struct:将字

python核心编程--笔记

python核心编程--笔记 的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找python路径 1.4 –v   冗余输出(导入语句详细追踪) 1.5 –m mod 将一个模块以脚本形式运行 1.6 –Q opt 除法选项(参阅文档) 1.7 –c cmd 运行以命令行字符串心事提交的python脚本 1.8 file   以给定的文件运行python脚本 2 _在解释器中表示最后

Python 基础 - Day 5 Learning Note - 模块 之 介绍篇

定义 模块(module)支持从逻辑上组织Python代码,本质就是.py结尾的python文件(e.g.文件名:test.py; 模块名:test),目的是实现某项功能.将其他模块属性附加到你的模块中的操作叫导入(import). 模块分为三类:标准库.开源模块(open source module)和自定义模块. 包(package)是一个有层次的文件目录结构, 定义了一个由模块和子包组成的python应用程序执行环境.和模块及类一样,也使用句点属性标识来访问他们的元素.使用标准的impor