asyncore
— Asynchronous socket handler异步套接字处理程序¶
Source code: Lib/asyncore.py
Deprecated since version 3.6: 自3.6版起已弃用:asyncore
will be removed in Python 3.12 (PEP 594). asyncore
将在Python 3.12(PEP 594)中删除。Please use 请改用asyncio
instead.asyncio
。
Note
This module exists for backwards compatibility only. 此模块仅用于向后兼容。For new code we recommend using 对于新代码,我们建议使用asyncio
.asyncio
。
This module provides the basic infrastructure for writing asynchronous socket service clients and servers.该模块提供了编写异步套接字服务客户端和服务器的基本基础结构。
There are only two ways to have a program on a single processor do “more than one thing at a time.” 只有两种方法可以让一个处理器上的程序“一次做多件事”。Multi-threaded programming is the simplest and most popular way to do it, but there is another very different technique, that lets you have nearly all the advantages of multi-threading, without actually using multiple threads. 多线程编程是最简单和最流行的方法,但还有另一种非常不同的技术,它可以让您几乎拥有多线程的所有优点,而无需实际使用多线程。It’s really only practical if your program is largely I/O bound. 只有当程序在很大程度上受I/O限制时,它才真正实用。If your program is processor bound, then pre-emptive scheduled threads are probably what you really need. Network servers are rarely processor bound, however.如果您的程序是处理器绑定的,那么抢占式调度线程可能是您真正需要的。然而,网络服务器很少受处理器限制。
If your operating system supports the 如果您的操作系统支持其I/O库中的select()
system call in its I/O library (and nearly all do), then you can use it to juggle multiple communication channels at once; doing other work while your I/O is taking place in the “background.” select()
系统调用(几乎所有的都支持),那么您可以使用它同时处理多个通信通道;在“后台”进行I/O时执行其他工作。 Although this strategy can seem strange and complex, especially at first, it is in many ways easier to understand and control than multi-threaded programming. 尽管这种策略看起来很奇怪和复杂,尤其是在一开始,但在许多方面,它比多线程编程更容易理解和控制。The asyncore
module solves many of the difficult problems for you, making the task of building sophisticated high-performance network servers and clients a snap. asyncore
模块为您解决了许多难题,使构建复杂的高性能网络服务器和客户端的任务变得轻而易举。For “conversational” applications and protocols the companion 对于“对话式”应用程序和协议,伴随的asynchat
module is invaluable.asynchat
模块是非常宝贵的。
The basic idea behind both modules is to create one or more network channels, instances of class 这两个模块背后的基本思想是创建一个或多个网络channels,即类asyncore.dispatcher
and asynchat.async_chat
. asyncore.dispatcher
和asynchat.async_chat
的实例。Creating the channels adds them to a global map, used by the 创建通道会将它们添加到全局映射中,如果不提供自己的map,loop()
function if you do not provide it with your own map.loop()
函数将使用该映射。
Once the initial channel(s) is(are) created, calling the 一旦创建了初始通道,调用loop()
function activates channel service, which continues until the last channel (including any that have been added to the map during asynchronous service) is closed.loop()
函数将激活通道服务,直到最后一个通道(包括在异步服务期间添加到映射中的任何通道)关闭。
-
asyncore.
loop
([timeout[, use_poll[, map[, count]]]])¶ Enter a polling loop that terminates after count passes or all open channels have been closed.进入一个轮询循环,该循环在计数通过或所有打开的通道关闭后终止。All arguments are optional.所有参数都是可选的。The count parameter defaults tocount参数默认为None
, resulting in the loop terminating only when all channels have been closed.None
,导致循环仅在所有通道关闭时终止。The timeout argument sets the timeout parameter for the appropriatetimeout参数为适当的select()
orpoll()
call, measured in seconds; the default is 30 seconds.select()
或poll()
调用设置超时参数,以秒为单位;默认值为30秒。The use_poll parameter, if true, indicates thatuse_poll参数如果为poll()
should be used in preference toselect()
(the default isFalse
).true
,则表示应优先使用poll()
而不是select()
(默认值为False
)。The map parameter is a dictionary whose items are the channels to watch.map参数是一个字典,其项是要观看的频道。As channels are closed they are deleted from their map.当通道关闭时,它们将从其地图中删除。If map is omitted, a global map is used.如果省略map,则使用全局映射。Channels (instances of通道(asyncore.dispatcher
,asynchat.async_chat
and subclasses thereof) can freely be mixed in the map.asyncore.dispatcher
、asynchat.async_chat
及其子类的实例)可以在映射中自由混合。
-
class
asyncore.
dispatcher
¶ Thedispatcher
class is a thin wrapper around a low-level socket object.dispatcher
类是一个围绕低级套接字对象的瘦包装器。To make it more useful, it has a few methods for event-handling which are called from the asynchronous loop.为了使它更有用,它有一些从异步循环调用的事件处理方法。Otherwise, it can be treated as a normal non-blocking socket object.否则,可以将其视为正常的非阻塞套接字对象。The firing of low-level events at certain times or in certain connection states tells the asynchronous loop that certain higher-level events have taken place.在特定时间或特定连接状态下触发低级事件告诉异步循环已发生某些高级事件。For example, if we have asked for a socket to connect to another host, we know that the connection has been made when the socket becomes writable for the first time (at this point you know that you may write to it with the expectation of success).例如,如果我们请求一个套接字连接到另一个主机,那么当套接字第一次变为可写时,我们就知道已经建立了连接(此时,您知道您可能会在期望成功的情况下写入该套接字)。The implied higher-level events are:隐含的高级事件包括:Event事件Description描述handle_connect()
Implied by the first read or write event由第一个读或写事件暗示handle_close()
Implied by a read event with no data available由没有可用数据的读取事件暗示handle_accepted()
Implied by a read event on a listening socket由侦听套接字上的读取事件暗示During asynchronous processing, each mapped channel’s在异步处理期间,每个映射通道的readable()
andwritable()
methods are used to determine whether the channel’s socket should be added to the list of channelsselect()
ed orpoll()
ed for read and write events.readable()
和writable()
方法用于确定是否应将通道的套接字添加到读取和写入事件的通道selected()
或poll()
ed列表中。Thus, the set of channel events is larger than the basic socket events.因此,通道事件集大于基本套接字事件集。The full set of methods that can be overridden in your subclass follows:可以在子类中重写的完整方法集如下:-
handle_read
()¶ Called when the asynchronous loop detects that a当异步循环检测到通道套接字上的read()
call on the channel’s socket will succeed.read()
调用将成功时调用。
-
handle_write
()¶ Called when the asynchronous loop detects that a writable socket can be written.当异步循环检测到可以写入可写套接字时调用。Often this method will implement the necessary buffering for performance.通常,此方法将实现性能所需的缓冲。For example:例如:def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
-
handle_expt
()¶ Called when there is out of band (OOB) data for a socket connection.当套接字连接存在带外(OOB)数据时调用。This will almost never happen, as OOB is tenuously supported and rarely used.这几乎永远不会发生,因为OOB很少得到支持和使用。
-
handle_connect
()¶ Called when the active opener’s socket actually makes a connection.当活动开启器的套接字实际建立连接时调用。Might send a “welcome” banner, or initiate a protocol negotiation with the remote endpoint, for example.例如,可能会发送“欢迎”横幅,或启动与远程端点的协议协商。
-
handle_close
()¶ Called when the socket is closed.当套接字关闭时调用。
-
handle_error
()¶ Called when an exception is raised and not otherwise handled.在引发异常且未以其他方式处理时调用。The default version prints a condensed traceback.默认版本打印精简的回溯。
-
handle_accept
()¶ Called on listening channels (passive openers) when a connection can be established with a new remote endpoint that has issued a当可以与已为本地端点发出connect()
call for the local endpoint.connect()
调用的新远程端点建立连接时,在侦听通道(被动开启器)上调用。Deprecated in version 3.2; use3.2版已弃用;请改用handle_accepted()
instead.handle_accepted()
。Deprecated since version 3.2.自3.2版起已弃用。
-
handle_accepted
(sock, addr)¶ Called on listening channels (passive openers) when a connection has been established with a new remote endpoint that has issued a当与新的远程端点建立连接时,在侦听通道(被动开启器)上调用,该远程端点已为本地端点发出connect()
call for the local endpoint.connect()
调用。sock is a new socket object usable to send and receive data on the connection, and addr is the address bound to the socket on the other end of the connection.sock是一个new套接字对象,可用于在连接上发送和接收数据,addr是绑定到连接另一端套接字的地址。New in version 3.2.版本3.2中新增。
-
readable
()¶ Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which read events can occur.每次在异步循环中调用,以确定是否应将通道的套接字添加到可发生读取事件的列表中。The default method simply returns默认方法只返回True
, indicating that by default, all channels will be interested in read events.True
,表示默认情况下,所有通道都对读取事件感兴趣。
-
writable
()¶ Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which write events can occur.每次在异步循环中调用,以确定是否应将通道的套接字添加到可发生写入事件的列表中。The default method simply returns默认方法只返回True
, indicating that by default, all channels will be interested in write events.True
,表示默认情况下,所有通道都对写入事件感兴趣。
In addition, each channel delegates or extends many of the socket methods.此外,每个通道代理或扩展许多套接字方法。Most of these are nearly identical to their socket partners.其中大多数与它们的套接字伙伴几乎相同。-
create_socket
(family=socket.AF_INET, type=socket.SOCK_STREAM)¶ This is identical to the creation of a normal socket, and will use the same options for creation.这与创建普通套接字相同,并将使用相同的选项进行创建。Refer to the有关创建套接字的信息,请参阅socket
documentation for information on creating sockets.socket
文档。Changed in version 3.3:版本3.3中更改:family and type arguments can be omitted.family和type参数可以省略。
-
connect
(address)¶ As with the normal socket object, address is a tuple with the first element the host to connect to, and the second the port number.与普通套接字对象一样,address是一个元组,第一个元素是主机要连接的,第二个元素是端口号。
-
send
(data)¶ Send data to the remote end-point of the socket.将data发送到套接字的远程端点。
-
recv
(buffer_size)¶ Read at most buffer_size bytes from the socket’s remote end-point.从套接字的远程端点读取最多buffer_size字节。An empty bytes object implies that the channel has been closed from the other end.空字节对象表示通道已从另一端关闭。Note that请注意,recv()
may raiseBlockingIOError
, even thoughselect.select()
orselect.poll()
has reported the socket ready for reading.recv()
可能会引发BlockingIOError
,即使select.select()
orselect.poll()
或select.poll()
已报告套接字已准备好读取。
-
listen
(backlog)¶ Listen for connections made to the socket.倾听插座的连接。The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).backlog参数指定排队连接的最大数量,并且应至少为1;最大值取决于系统(通常为5)。
-
bind
(address)¶ Bind the socket to address.将套接字绑定到address。The socket must not already be bound.套接字必须尚未绑定。(The format of address depends on the address family — refer to the(address的格式取决于地址系列-有关详细信息,请参阅socket
documentation for more information.)socket
文档。)To mark the socket as re-usable (setting the要将套接字标记为可重用(设置SO_REUSEADDR
option), call thedispatcher
object’sset_reuse_addr()
method.SO_REUSEADDR
选项),请调用dispatcher
对象的set_reuse_addr()
方法。
-
accept
()¶ Accept a connection. The socket must be bound to an address and listening for connections.接受连接。套接字必须绑定到地址并侦听连接。The return value can be either返回值可以是None
or a pair(conn, address)
where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.None
或一对(conn, address)
,其中conn是可用于在连接上发送和接收数据的new套接字对象,address是绑定到连接另一端套接字的地址。When如果返回None
is returned it means the connection didn’t take place, in which case the server should just ignore this event and keep listening for further incoming connections.None
,则表示连接未发生,在这种情况下,服务器应忽略此事件并继续侦听其他传入连接。
-
close
()¶ Close the socket. All future operations on the socket object will fail.关闭插座。套接字对象上的所有未来操作都将失败。The remote end-point will receive no more data (after queued data is flushed).远程端点将不再接收数据(刷新排队数据后)。Sockets are automatically closed when they are garbage-collected.套接字在垃圾收集时自动关闭。
-
-
class
asyncore.
dispatcher_with_send
¶ A一个dispatcher
subclass which adds simple buffered output capability, useful for simple clients.dispatcher
子类,它添加了简单的缓冲输出功能,对简单客户端很有用。For more sophisticated usage use要获得更复杂的用法,请使用asynchat.async_chat
.asynchat.async_chat
。
-
class
asyncore.
file_dispatcher
¶ A file_dispatcher takes a file descriptor or file object along with an optional map argument and wraps it for use with thefile_dispatcher获取一个文件描述符或文件对象以及一个可选的map参数,并将其包装起来,以便与poll()
orloop()
functions.poll()
或loop()
函数一起使用。If provided a file object or anything with a如果提供了一个文件对象或任何带有fileno()
method, that method will be called and passed to thefile_wrapper
constructor.fileno()
方法的东西,那么将调用该方法并将其传递给file_wrapper
构造函数。Availability: Unix.
-
class
asyncore.
file_wrapper
¶ A file_wrapper takes an integer file descriptor and callsfile_wrapper获取一个整数文件描述符,并调用os.dup()
to duplicate the handle so that the original handle may be closed independently of the file_wrapper.os.dup()
来复制句柄,以便可以独立于file_wraper关闭原始句柄。This class implements sufficient methods to emulate a socket for use by the该类实现了足够的方法来模拟file_dispatcher
class.file_dispatcher
类使用的套接字。Availability: Unix.
asyncore Example basic HTTP client异步示例基本HTTP客户端¶
Here is a very basic HTTP client that uses the 下面是一个非常基本的HTTP客户端,它使用dispatcher
class to implement its socket handling:dispatcher
类来实现其套接字处理:
import asyncore
class HTTPClient(asyncore.dispatcher):
def __init__(self, host, path):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.connect( (host, 80) )
self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
(path, host), 'ascii')
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 = HTTPClient('www.python.org', '/')
asyncore.loop()
asyncore Example basic echo server异步示例基本echo服务器¶
Here is a basic echo server that uses the 这里是一个基本的echo服务器,它使用dispatcher
class to accept connections and dispatches the incoming connections to a handler:dispatcher
类接受连接并将传入的连接分派给处理程序:
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()
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
def handle_accepted(self, sock, addr):
print('Incoming connection from %s' % repr(addr))
handler = EchoHandler(sock)
server = EchoServer('localhost', 8080)
asyncore.loop()