Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`asyncore` --- Asynchronous socket handler |
| 3 | =============================================== |
| 4 | |
| 5 | .. module:: asyncore |
| 6 | :synopsis: A base class for developing asynchronous socket handling services. |
| 7 | .. moduleauthor:: Sam Rushing <rushing@nightmare.com> |
| 8 | .. sectionauthor:: Christopher Petrilli <petrilli@amber.org> |
| 9 | .. sectionauthor:: Steve Holden <sholden@holdenweb.com> |
| 10 | |
| 11 | |
| 12 | This module provides the basic infrastructure for writing asynchronous socket |
| 13 | service clients and servers. |
| 14 | |
| 15 | .. % Heavily adapted from original documentation by Sam Rushing. |
| 16 | |
| 17 | There are only two ways to have a program on a single processor do "more than |
| 18 | one thing at a time." Multi-threaded programming is the simplest and most |
| 19 | popular way to do it, but there is another very different technique, that lets |
| 20 | you have nearly all the advantages of multi-threading, without actually using |
| 21 | multiple threads. It's really only practical if your program is largely I/O |
| 22 | 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, |
| 24 | however. |
| 25 | |
| 26 | 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 |
| 28 | communication channels at once; doing other work while your I/O is taking place |
| 29 | in the "background." Although this strategy can seem strange and complex, |
| 30 | especially at first, it is in many ways easier to understand and control than |
| 31 | multi-threaded programming. The :mod:`asyncore` module solves many of the |
| 32 | difficult problems for you, making the task of building sophisticated |
| 33 | high-performance network servers and clients a snap. For "conversational" |
| 34 | applications and protocols the companion :mod:`asynchat` module is invaluable. |
| 35 | |
| 36 | The basic idea behind both modules is to create one or more network *channels*, |
| 37 | instances of class :class:`asyncore.dispatcher` and |
| 38 | :class:`asynchat.async_chat`. Creating the channels adds them to a global map, |
| 39 | used by the :func:`loop` function if you do not provide it with your own *map*. |
| 40 | |
| 41 | Once the initial channel(s) is(are) created, calling the :func:`loop` function |
| 42 | activates channel service, which continues until the last channel (including any |
| 43 | that have been added to the map during asynchronous service) is closed. |
| 44 | |
| 45 | |
| 46 | .. function:: loop([timeout[, use_poll[, map[,count]]]]) |
| 47 | |
| 48 | Enter a polling loop that terminates after count passes or all open channels |
| 49 | have been closed. All arguments are optional. The *count* parameter defaults |
| 50 | to None, resulting in the loop terminating only when all channels have been |
| 51 | closed. The *timeout* argument sets the timeout parameter for the appropriate |
| 52 | :func:`select` or :func:`poll` call, measured in seconds; the default is 30 |
| 53 | seconds. The *use_poll* parameter, if true, indicates that :func:`poll` should |
| 54 | be used in preference to :func:`select` (the default is ``False``). |
| 55 | |
| 56 | The *map* parameter is a dictionary whose items are the channels to watch. As |
| 57 | channels are closed they are deleted from their map. If *map* is omitted, a |
| 58 | global map is used. Channels (instances of :class:`asyncore.dispatcher`, |
| 59 | :class:`asynchat.async_chat` and subclasses thereof) can freely be mixed in the |
| 60 | map. |
| 61 | |
| 62 | |
| 63 | .. class:: dispatcher() |
| 64 | |
| 65 | The :class:`dispatcher` class is a thin wrapper around a low-level socket |
| 66 | object. To make it more useful, it has a few methods for event-handling which |
| 67 | are called from the asynchronous loop. Otherwise, it can be treated as a |
| 68 | normal non-blocking socket object. |
| 69 | |
| 70 | 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 |
| 84 | tells the asynchronous loop that certain higher-level events have taken place. |
| 85 | For example, if we have asked for a socket to connect to another host, we know |
| 86 | that the connection has been made when the socket becomes writable for the first |
| 87 | time (at this point you know that you may write to it with the expectation of |
| 88 | success). The implied higher-level 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 |
| 104 | should be added to the list of channels :cfunc:`select`\ ed or :cfunc:`poll`\ ed |
| 105 | for read and write events. |
| 106 | |
| 107 | Thus, the set of channel events is larger than the basic socket events. The full |
| 108 | set of methods that can be overridden in your subclass follows: |
| 109 | |
| 110 | |
| 111 | .. method:: dispatcher.handle_read() |
| 112 | |
| 113 | Called when the asynchronous loop detects that a :meth:`read` call on the |
| 114 | channel's socket will succeed. |
| 115 | |
| 116 | |
| 117 | .. method:: dispatcher.handle_write() |
| 118 | |
| 119 | Called when the asynchronous loop detects that a writable socket can be written. |
| 120 | Often this method will implement the necessary buffering for performance. For |
| 121 | example:: |
| 122 | |
| 123 | def handle_write(self): |
| 124 | sent = self.send(self.buffer) |
| 125 | self.buffer = self.buffer[sent:] |
| 126 | |
| 127 | |
| 128 | .. method:: dispatcher.handle_expt() |
| 129 | |
| 130 | Called when there is out of band (OOB) data for a socket connection. This will |
| 131 | almost never happen, as OOB is tenuously supported and rarely used. |
| 132 | |
| 133 | |
| 134 | .. method:: dispatcher.handle_connect() |
| 135 | |
| 136 | Called when the active opener's socket actually makes a connection. Might send a |
| 137 | "welcome" banner, or initiate a protocol negotiation with the remote endpoint, |
| 138 | for example. |
| 139 | |
| 140 | |
| 141 | .. method:: dispatcher.handle_close() |
| 142 | |
| 143 | Called when the socket is closed. |
| 144 | |
| 145 | |
| 146 | .. method:: dispatcher.handle_error() |
| 147 | |
| 148 | Called when an exception is raised and not otherwise handled. The default |
| 149 | version prints a condensed traceback. |
| 150 | |
| 151 | |
| 152 | .. method:: dispatcher.handle_accept() |
| 153 | |
| 154 | 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 |
| 156 | for the local endpoint. |
| 157 | |
| 158 | |
| 159 | .. method:: dispatcher.readable() |
| 160 | |
| 161 | Called each time around the asynchronous loop to determine whether a channel's |
| 162 | socket should be added to the list on which read events can occur. The default |
| 163 | method simply returns ``True``, indicating that by default, all channels will |
| 164 | be interested in read events. |
| 165 | |
| 166 | |
| 167 | .. method:: dispatcher.writable() |
| 168 | |
| 169 | Called each time around the asynchronous loop to determine whether a channel's |
| 170 | socket should be added to the list on which write events can occur. The default |
| 171 | method simply returns ``True``, indicating that by default, all channels will |
| 172 | be interested in write events. |
| 173 | |
| 174 | In addition, each channel delegates or extends many of the socket methods. Most |
| 175 | of these are nearly identical to their socket partners. |
| 176 | |
| 177 | |
| 178 | .. method:: dispatcher.create_socket(family, type) |
| 179 | |
| 180 | This is identical to the creation of a normal socket, and will use the same |
| 181 | options for creation. Refer to the :mod:`socket` documentation for information |
| 182 | on creating sockets. |
| 183 | |
| 184 | |
| 185 | .. method:: dispatcher.connect(address) |
| 186 | |
| 187 | As with the normal socket object, *address* is a tuple with the first element |
| 188 | the host to connect to, and the second the port number. |
| 189 | |
| 190 | |
| 191 | .. method:: dispatcher.send(data) |
| 192 | |
| 193 | Send *data* to the remote end-point of the socket. |
| 194 | |
| 195 | |
| 196 | .. method:: dispatcher.recv(buffer_size) |
| 197 | |
| 198 | Read at most *buffer_size* bytes from the socket's remote end-point. An empty |
| 199 | string implies that the channel has been closed from the other end. |
| 200 | |
| 201 | |
| 202 | .. method:: dispatcher.listen(backlog) |
| 203 | |
| 204 | Listen for connections made to the socket. The *backlog* argument specifies the |
| 205 | maximum number of queued connections and should be at least 1; the maximum value |
| 206 | is system-dependent (usually 5). |
| 207 | |
| 208 | |
| 209 | .. method:: dispatcher.bind(address) |
| 210 | |
| 211 | Bind the socket to *address*. The socket must not already be bound. (The |
| 212 | format of *address* depends on the address family --- see above.) To mark the |
| 213 | socket as re-usable (setting the :const:`SO_REUSEADDR` option), call the |
| 214 | :class:`dispatcher` object's :meth:`set_reuse_addr` method. |
| 215 | |
| 216 | |
| 217 | .. method:: dispatcher.accept() |
| 218 | |
| 219 | Accept a connection. The socket must be bound to an address and listening for |
| 220 | connections. The return value is a pair ``(conn, address)`` where *conn* is a |
| 221 | *new* socket object usable to send and receive data on the connection, and |
| 222 | *address* is the address bound to the socket on the other end of the connection. |
| 223 | |
| 224 | |
| 225 | .. method:: dispatcher.close() |
| 226 | |
| 227 | Close the socket. All future operations on the socket object will fail. The |
| 228 | remote end-point will receive no more data (after queued data is flushed). |
| 229 | Sockets are automatically closed when they are garbage-collected. |
| 230 | |
| 231 | |
| 232 | .. _asyncore-example: |
| 233 | |
| 234 | asyncore Example basic HTTP client |
| 235 | ---------------------------------- |
| 236 | |
| 237 | Here is a very basic HTTP client that uses the :class:`dispatcher` class to |
| 238 | implement its socket handling:: |
| 239 | |
| 240 | import asyncore, socket |
| 241 | |
| 242 | class http_client(asyncore.dispatcher): |
| 243 | |
| 244 | def __init__(self, host, path): |
| 245 | asyncore.dispatcher.__init__(self) |
| 246 | self.create_socket(socket.AF_INET, socket.SOCK_STREAM) |
| 247 | self.connect( (host, 80) ) |
| 248 | self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % path |
| 249 | |
| 250 | def handle_connect(self): |
| 251 | pass |
| 252 | |
| 253 | def handle_close(self): |
| 254 | self.close() |
| 255 | |
| 256 | def handle_read(self): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame^] | 257 | print(self.recv(8192)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 258 | |
| 259 | def writable(self): |
| 260 | return (len(self.buffer) > 0) |
| 261 | |
| 262 | def handle_write(self): |
| 263 | sent = self.send(self.buffer) |
| 264 | self.buffer = self.buffer[sent:] |
| 265 | |
| 266 | c = http_client('www.python.org', '/') |
| 267 | |
| 268 | asyncore.loop() |
| 269 | |