rest25/library/asyncore.rst => rest262/library/asyncore.rst
f1
2:mod:`asyncore` --- Asynchronous socket handler
3===============================================
4
5.. module:: asyncore
n6-   :synopsis: A base class for developing asynchronous socket  handling services.
n6+   :synopsis: A base class for developing asynchronous socket handling
7+              services.
7.. moduleauthor:: Sam Rushing <rushing@nightmare.com>
8.. sectionauthor:: Christopher Petrilli <petrilli@amber.org>
9.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
n11+.. heavily adapted from original documentation by Sam Rushing
10
11
12This module provides the basic infrastructure for writing asynchronous  socket
13service clients and servers.
14
n15-.. % Heavily adapted from original documentation by Sam Rushing.
16- 
17There are only two ways to have a program on a single processor do  "more than
18one thing at a time." Multi-threaded programming is the  simplest and most
n19-popular way to do it, but there is another very  different technique, that lets
n19+popular way to do it, but there is another very different technique, that lets
20you have nearly all the advantages of  multi-threading, without actually using
21multiple threads.  It's really  only practical if your program is largely I/O
n22-bound.  If your program  is processor bound, then pre-emptive scheduled threads
n22+bound.  If your program is processor bound, then pre-emptive scheduled threads
23-are probably what  you really need. Network servers are rarely processor bound,
23+are probably what you really need.  Network servers are rarely processor
24-however.
24+bound, however.
25
n26-If your operating system supports the :cfunc:`select` system call  in its I/O
n26+If your operating system supports the :cfunc:`select` system call in its I/O
27-library (and nearly all do), then you can use it to juggle  multiple
27+library (and nearly all do), then you can use it to juggle multiple
28-communication channels at once; doing other work while your  I/O is taking place
28+communication channels at once; doing other work while your I/O is taking
29-in the "background."  Although this strategy can  seem strange and complex,
29+place in the "background."  Although this strategy can seem strange and
30-especially at first, it is in many ways  easier to understand and control than
30+complex, especially at first, it is in many ways easier to understand and
31-multi-threaded programming.   The :mod:`asyncore` module solves many of the
31+control than multi-threaded programming.  The :mod:`asyncore` module solves
32-difficult problems for  you, making the task of building sophisticated high-
32+many of the difficult problems for you, making the task of building
33-performance  network servers and clients a snap. For "conversational"
33+sophisticated high-performance network servers and clients a snap.  For
34-applications and protocols the companion  :mod:`asynchat` module is invaluable.
34+"conversational" applications and protocols the companion :mod:`asynchat`
35+module is invaluable.
35
n36-The basic idea behind both modules is to create one or more network *channels*,
n37+The basic idea behind both modules is to create one or more network
37-instances of class :class:`asyncore.dispatcher` and
38+*channels*, instances of class :class:`asyncore.dispatcher` and
38-:class:`asynchat.async_chat`. Creating the channels adds them to a global map,
39+:class:`asynchat.async_chat`.  Creating the channels adds them to a global
39-used by the :func:`loop` function if you do not provide it with your own *map*.
40+map, used by the :func:`loop` function if you do not provide it with your own
41+*map*.
40
41Once the initial channel(s) is(are) created, calling the :func:`loop` function
n42-activates channel service, which continues until the last channel (including any
n44+activates channel service, which continues until the last channel (including
43-that have been added to the map during asynchronous service) is closed.
45+any that have been added to the map during asynchronous service) is closed.
44
45
46.. function:: loop([timeout[, use_poll[, map[,count]]]])
47
n48-   Enter a polling loop that terminates after count passes or all open channels
n50+   Enter a polling loop that terminates after count passes or all open
49-   have been closed.  All arguments are optional.  The *(*count) parameter defaults
51+   channels have been closed.  All arguments are optional.  The *count*
50-   to None, resulting in the loop terminating only when all channels have been
52+   parameter defaults to None, resulting in the loop terminating only when all
51-   closed.  The *timeout* argument sets the timeout parameter for the appropriate
53+   channels have been closed.  The *timeout* argument sets the timeout
52-   :func:`select` or :func:`poll` call, measured in seconds; the default is 30
54+   parameter for the appropriate :func:`select` or :func:`poll` call, measured
53-   seconds. The *use_poll* parameter, if true, indicates that :func:`poll` should
55+   in seconds; the default is 30 seconds.  The *use_poll* parameter, if true,
54-   be used in preference to :func:`select` (the default is ``False``).
56+   indicates that :func:`poll` should be used in preference to :func:`select`
57+   (the default is ``False``).
55
n56-   The *map* parameter is a dictionary whose items are the channels to watch.  As
n59+   The *map* parameter is a dictionary whose items are the channels to watch.
57-   channels are closed they are deleted from their map.  If *map* is omitted, a
60+   As channels are closed they are deleted from their map.  If *map* is
58-   global map is used. Channels (instances of :class:`asyncore.dispatcher`,
61+   omitted, a global map is used. Channels (instances of
59-   :class:`asynchat.async_chat` and subclasses thereof) can freely be mixed in the
62+   :class:`asyncore.dispatcher`, :class:`asynchat.async_chat` and subclasses
60-   map.
63+   thereof) can freely be mixed in the map.
61
62
63.. class:: dispatcher()
64
65   The :class:`dispatcher` class is a thin wrapper around a low-level socket
n66-   object. To make it more useful, it has a few methods for event-handling  which
n69+   object. To make it more useful, it has a few methods for event-handling
67-   are called from the asynchronous loop.   Otherwise, it can be treated as a
70+   which are called from the asynchronous loop.   Otherwise, it can be treated
68-   normal non-blocking socket object.
71+   as a normal non-blocking socket object.
69
n70-   Two class attributes can be modified, to improve performance, or possibly even
71-   to conserve memory.
72- 
73- 
74-   .. data:: ac_in_buffer_size
75- 
76-      The asynchronous input buffer size (default ``4096``).
77- 
78- 
79-   .. data:: ac_out_buffer_size
80- 
81-      The asynchronous output buffer size (default ``4096``).
82- 
83-   The firing of low-level events at certain times or in certain connection states
73+   The firing of low-level events at certain times or in certain connection
84-   tells the asynchronous loop that certain higher-level events have taken place.
74+   states tells the asynchronous loop that certain higher-level events have
85-   For example, if we have asked for a socket to connect to another host, we know
75+   taken place.  For example, if we have asked for a socket to connect to
86-   that the connection has been made when the socket becomes writable for the first
76+   another host, we know that the connection has been made when the socket
87-   time (at this point you know that you may write to it with the expectation of
77+   becomes writable for the first time (at this point you know that you may
88-   success). The implied higher-level events are:
78+   write to it with the expectation of success).  The implied higher-level
79+   events are:
89
90   +----------------------+----------------------------------------+
91   | Event                | Description                            |
92   +======================+========================================+
93   | ``handle_connect()`` | Implied by the first write event       |
94   +----------------------+----------------------------------------+
95   | ``handle_close()``   | Implied by a read event with no data   |
96   |                      | available                              |
97   +----------------------+----------------------------------------+
98   | ``handle_accept()``  | Implied by a read event on a listening |
99   |                      | socket                                 |
100   +----------------------+----------------------------------------+
101
102   During asynchronous processing, each mapped channel's :meth:`readable` and
103   :meth:`writable` methods are used to determine whether the channel's socket
n104-   should be added to the list of channels :cfunc:`select`\ ed or :cfunc:`poll`\ ed
n95+   should be added to the list of channels :cfunc:`select`\ ed or
105-   for read and write events.
96+   :cfunc:`poll`\ ed for read and write events.
106
n107-Thus, the set of channel events is larger than the basic socket events. The full
n98+   Thus, the set of channel events is larger than the basic socket events.  The
108-set of methods that can be overridden in your subclass follows:
99+   full set of methods that can be overridden in your subclass follows:
109
110
n111-.. method:: dispatcher.handle_read()
n102+   .. method:: handle_read()
112
n113-   Called when the asynchronous loop detects that a :meth:`read` call on the
n104+      Called when the asynchronous loop detects that a :meth:`read` call on the
114-   channel's socket will succeed.
105+      channel's socket will succeed.
115
116
n117-.. method:: dispatcher.handle_write()
n108+   .. method:: handle_write()
118
n119-   Called when the asynchronous loop detects that a writable socket can be written.
n110+      Called when the asynchronous loop detects that a writable socket can be
120-   Often this method will implement the necessary buffering for  performance.  For
111+      written.  Often this method will implement the necessary buffering for
121-   example::
112+      performance.  For example::
122
n123-      def handle_write(self):
n114+         def handle_write(self):
124-          sent = self.send(self.buffer)
115+             sent = self.send(self.buffer)
125-          self.buffer = self.buffer[sent:]
116+             self.buffer = self.buffer[sent:]
126
127
n128-.. method:: dispatcher.handle_expt()
n119+   .. method:: handle_expt()
129
n130-   Called when there is out of band (OOB) data for a socket  connection.  This will
n121+      Called when there is out of band (OOB) data for a socket connection.  This
131-   almost never happen, as OOB is  tenuously supported and rarely used.
122+      will almost never happen, as OOB is tenuously supported and rarely used.
132
133
n134-.. method:: dispatcher.handle_connect()
n125+   .. method:: handle_connect()
135
n136-   Called when the active opener's socket actually makes a connection. Might send a
n127+      Called when the active opener's socket actually makes a connection.  Might
137-   "welcome" banner, or initiate a protocol negotiation with the remote endpoint,
128+      send a "welcome" banner, or initiate a protocol negotiation with the
138-   for example.
129+      remote endpoint, for example.
139
140
n141-.. method:: dispatcher.handle_close()
n132+   .. method:: handle_close()
142
n143-   Called when the socket is closed.
n134+      Called when the socket is closed.
144
145
n146-.. method:: dispatcher.handle_error()
n137+   .. method:: handle_error()
147
n148-   Called when an exception is raised and not otherwise handled.  The default
n139+      Called when an exception is raised and not otherwise handled.  The default
149-   version prints a condensed traceback.
140+      version prints a condensed traceback.
150
151
n152-.. method:: dispatcher.handle_accept()
n143+   .. method:: handle_accept()
153
n154-   Called on listening channels (passive openers) when a   connection can be
n145+      Called on listening channels (passive openers) when a connection can be
155-   established with a new remote endpoint that has issued a :meth:`connect` call
146+      established with a new remote endpoint that has issued a :meth:`connect`
156-   for the local endpoint.
147+      call for the local endpoint.
157
158
n159-.. method:: dispatcher.readable()
n150+   .. method:: readable()
160
n161-   Called each time around the asynchronous loop to determine whether a channel's
n152+      Called each time around the asynchronous loop to determine whether a
162-   socket should be added to the list on which read events can occur.  The default
153+      channel's socket should be added to the list on which read events can
163-   method simply returns ``True``,  indicating that by default, all channels will
154+      occur.  The default method simply returns ``True``, indicating that by
164-   be interested in read events.
155+      default, all channels will be interested in read events.
165
166
n167-.. method:: dispatcher.writable()
n158+   .. method:: writable()
168
n169-   Called each time around the asynchronous loop to determine whether a channel's
n160+      Called each time around the asynchronous loop to determine whether a
170-   socket should be added to the list on which write events can occur.  The default
161+      channel's socket should be added to the list on which write events can
171-   method simply returns ``True``,  indicating that by default, all channels will
162+      occur.  The default method simply returns ``True``, indicating that by
172-   be interested in write events.
163+      default, all channels will be interested in write events.
173
n165+ 
174-In addition, each channel delegates or extends many of the socket methods. Most
166+   In addition, each channel delegates or extends many of the socket methods.
175-of these are nearly identical to their socket partners.
167+   Most of these are nearly identical to their socket partners.
176
177
n178-.. method:: dispatcher.create_socket(family, type)
n170+   .. method:: create_socket(family, type)
179
n180-   This is identical to the creation of a normal socket, and  will use the same
n172+      This is identical to the creation of a normal socket, and will use the
181-   options for creation.  Refer to the :mod:`socket` documentation for information
173+      same options for creation.  Refer to the :mod:`socket` documentation for
182-   on creating sockets.
174+      information on creating sockets.
183
184
n185-.. method:: dispatcher.connect(address)
n177+   .. method:: connect(address)
186
n187-   As with the normal socket object, *address* is a  tuple with the first element
n179+      As with the normal socket object, *address* is a tuple with the first
188-   the host to connect to, and the  second the port number.
180+      element the host to connect to, and the second the port number.
189
190
n191-.. method:: dispatcher.send(data)
n183+   .. method:: send(data)
192
n193-   Send *data* to the remote end-point of the socket.
n185+      Send *data* to the remote end-point of the socket.
194
195
n196-.. method:: dispatcher.recv(buffer_size)
n188+   .. method:: recv(buffer_size)
197
n198-   Read at most *buffer_size* bytes from the socket's remote end-point. An empty
n190+      Read at most *buffer_size* bytes from the socket's remote end-point.  An
199-   string implies that the channel has been closed from the other end.
191+      empty string implies that the channel has been closed from the other end.
200
201
n202-.. method:: dispatcher.listen(backlog)
n194+   .. method:: listen(backlog)
203
n204-   Listen for connections made to the socket.  The *backlog* argument specifies the
n196+      Listen for connections made to the socket.  The *backlog* argument
205-   maximum number of queued connections and should be at least 1; the maximum value
197+      specifies the maximum number of queued connections and should be at least
206-   is system-dependent (usually 5).
198+      1; the maximum value is system-dependent (usually 5).
207
208
n209-.. method:: dispatcher.bind(address)
n201+   .. method:: bind(address)
210
n211-   Bind the socket to *address*.  The socket must not already be bound.  (The
n203+      Bind the socket to *address*.  The socket must not already be bound.  (The
212-   format of *address* depends on the address family --- see above.)
204+      format of *address* depends on the address family --- see above.)  To mark
205+      the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call
206+      the :class:`dispatcher` object's :meth:`set_reuse_addr` method.
213
214
n215-.. method:: dispatcher.accept()
n209+   .. method:: accept()
216
n217-   Accept a connection.  The socket must be bound to an address and listening for
n211+      Accept a connection.  The socket must be bound to an address and listening
218-   connections.  The return value is a pair ``(conn, address)`` where *conn* is a
212+      for connections.  The return value is a pair ``(conn, address)`` where
219-   *new* socket object usable to send and receive data on the connection, and
213+      *conn* is a *new* socket object usable to send and receive data on the
220-   *address* is the address bound to the socket on the other end of the connection.
214+      connection, and *address* is the address bound to the socket on the other
215+      end of the connection.
221
222
n223-.. method:: dispatcher.close()
n218+   .. method:: close()
224
n225-   Close the socket.  All future operations on the socket object will fail.  The
n220+      Close the socket.  All future operations on the socket object will fail.
226-   remote end-point will receive no more data (after queued data is flushed).
221+      The remote end-point will receive no more data (after queued data is
227-   Sockets are automatically closed when they are garbage-collected.
222+      flushed).  Sockets are automatically closed when they are
223+      garbage-collected.
224+ 
225+.. class:: file_dispatcher()
226+ 
227+   A file_dispatcher takes a file descriptor or file object along with an
228+   optional map argument and wraps it for use with the :cfunc:`poll` or
229+   :cfunc:`loop` functions.  If provided a file object or anything with a
230+   :cfunc:`fileno` method, that method will be called and passed to the
231+   :class:`file_wrapper` constructor.  Availability: UNIX.
232+ 
233+.. class:: file_wrapper()
234+ 
235+   A file_wrapper takes an integer file descriptor and calls :func:`os.dup` to
236+   duplicate the handle so that the original handle may be closed independently
237+   of the file_wrapper.  This class implements sufficient methods to emulate a
238+   socket for use by the :class:`file_dispatcher` class.  Availability: UNIX.
228
229
230.. _asyncore-example:
231
232asyncore Example basic HTTP client
233----------------------------------
234
235Here is a very basic HTTP client that uses the :class:`dispatcher` class to
259
260       def handle_write(self):
261           sent = self.send(self.buffer)
262           self.buffer = self.buffer[sent:]
263
264   c = http_client('www.python.org', '/')
265
266   asyncore.loop()
t267- 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op