1:mod:`asyncore` --- Asynchronous socket handler 2=============================================== 3 4.. module:: asyncore 5 :synopsis: A base class for developing asynchronous socket handling 6 services. 7 :deprecated: 8 9.. moduleauthor:: Sam Rushing <[email protected]> 10.. sectionauthor:: Christopher Petrilli <[email protected]> 11.. sectionauthor:: Steve Holden <[email protected]> 12.. heavily adapted from original documentation by Sam Rushing 13 14**Source code:** :source:`Lib/asyncore.py` 15 16.. deprecated-removed:: 3.6 3.12 17 The :mod:`asyncore` module is deprecated 18 (see :pep:`PEP 594 <594#asyncore>` for details). 19 Please use :mod:`asyncio` instead. 20 21-------------- 22 23.. note:: 24 25 This module exists for backwards compatibility only. For new code we 26 recommend using :mod:`asyncio`. 27 28This module provides the basic infrastructure for writing asynchronous socket 29service clients and servers. 30 31.. include:: ../includes/wasm-notavail.rst 32 33There are only two ways to have a program on a single processor do "more than 34one thing at a time." Multi-threaded programming is the simplest and most 35popular way to do it, but there is another very different technique, that lets 36you have nearly all the advantages of multi-threading, without actually using 37multiple threads. It's really only practical if your program is largely I/O 38bound. If your program is processor bound, then pre-emptive scheduled threads 39are probably what you really need. Network servers are rarely processor 40bound, however. 41 42If your operating system supports the :c:func:`select` system call in its I/O 43library (and nearly all do), then you can use it to juggle multiple 44communication channels at once; doing other work while your I/O is taking 45place in the "background." Although this strategy can seem strange and 46complex, especially at first, it is in many ways easier to understand and 47control than multi-threaded programming. The :mod:`asyncore` module solves 48many of the difficult problems for you, making the task of building 49sophisticated high-performance network servers and clients a snap. For 50"conversational" applications and protocols the companion :mod:`asynchat` 51module is invaluable. 52 53The basic idea behind both modules is to create one or more network 54*channels*, instances of class :class:`asyncore.dispatcher` and 55:class:`asynchat.async_chat`. Creating the channels adds them to a global 56map, used by the :func:`loop` function if you do not provide it with your own 57*map*. 58 59Once the initial channel(s) is(are) created, calling the :func:`loop` function 60activates channel service, which continues until the last channel (including 61any that have been added to the map during asynchronous service) is closed. 62 63 64.. function:: loop([timeout[, use_poll[, map[,count]]]]) 65 66 Enter a polling loop that terminates after count passes or all open 67 channels have been closed. All arguments are optional. The *count* 68 parameter defaults to ``None``, resulting in the loop terminating only when all 69 channels have been closed. The *timeout* argument sets the timeout 70 parameter for the appropriate :func:`~select.select` or :func:`~select.poll` 71 call, measured in seconds; the default is 30 seconds. The *use_poll* 72 parameter, if true, indicates that :func:`~select.poll` should be used in 73 preference to :func:`~select.select` (the default is ``False``). 74 75 The *map* parameter is a dictionary whose items are the channels to watch. 76 As channels are closed they are deleted from their map. If *map* is 77 omitted, a global map is used. Channels (instances of 78 :class:`asyncore.dispatcher`, :class:`asynchat.async_chat` and subclasses 79 thereof) can freely be mixed in the map. 80 81 82.. class:: dispatcher() 83 84 The :class:`dispatcher` class is a thin wrapper around a low-level socket 85 object. To make it more useful, it has a few methods for event-handling 86 which are called from the asynchronous loop. Otherwise, it can be treated 87 as a normal non-blocking socket object. 88 89 The firing of low-level events at certain times or in certain connection 90 states tells the asynchronous loop that certain higher-level events have 91 taken place. For example, if we have asked for a socket to connect to 92 another host, we know that the connection has been made when the socket 93 becomes writable for the first time (at this point you know that you may 94 write to it with the expectation of success). The implied higher-level 95 events are: 96 97 +----------------------+----------------------------------------+ 98 | Event | Description | 99 +======================+========================================+ 100 | ``handle_connect()`` | Implied by the first read or write | 101 | | event | 102 +----------------------+----------------------------------------+ 103 | ``handle_close()`` | Implied by a read event with no data | 104 | | available | 105 +----------------------+----------------------------------------+ 106 | ``handle_accepted()``| Implied by a read event on a listening | 107 | | socket | 108 +----------------------+----------------------------------------+ 109 110 During asynchronous processing, each mapped channel's :meth:`readable` and 111 :meth:`writable` methods are used to determine whether the channel's socket 112 should be added to the list of channels :c:func:`select`\ ed or 113 :c:func:`poll`\ ed for read and write events. 114 115 Thus, the set of channel events is larger than the basic socket events. The 116 full set of methods that can be overridden in your subclass follows: 117 118 119 .. method:: handle_read() 120 121 Called when the asynchronous loop detects that a :meth:`read` call on the 122 channel's socket will succeed. 123 124 125 .. method:: handle_write() 126 127 Called when the asynchronous loop detects that a writable socket can be 128 written. Often this method will implement the necessary buffering for 129 performance. For example:: 130 131 def handle_write(self): 132 sent = self.send(self.buffer) 133 self.buffer = self.buffer[sent:] 134 135 136 .. method:: handle_expt() 137 138 Called when there is out of band (OOB) data for a socket connection. This 139 will almost never happen, as OOB is tenuously supported and rarely used. 140 141 142 .. method:: handle_connect() 143 144 Called when the active opener's socket actually makes a connection. Might 145 send a "welcome" banner, or initiate a protocol negotiation with the 146 remote endpoint, for example. 147 148 149 .. method:: handle_close() 150 151 Called when the socket is closed. 152 153 154 .. method:: handle_error() 155 156 Called when an exception is raised and not otherwise handled. The default 157 version prints a condensed traceback. 158 159 160 .. method:: handle_accept() 161 162 Called on listening channels (passive openers) when a connection can be 163 established with a new remote endpoint that has issued a :meth:`connect` 164 call for the local endpoint. Deprecated in version 3.2; use 165 :meth:`handle_accepted` instead. 166 167 .. deprecated:: 3.2 168 169 170 .. method:: handle_accepted(sock, addr) 171 172 Called on listening channels (passive openers) when a connection has been 173 established with a new remote endpoint that has issued a :meth:`connect` 174 call for the local endpoint. *sock* is a *new* socket object usable to 175 send and receive data on the connection, and *addr* is the address 176 bound to the socket on the other end of the connection. 177 178 .. versionadded:: 3.2 179 180 181 .. method:: readable() 182 183 Called each time around the asynchronous loop to determine whether a 184 channel's socket should be added to the list on which read events can 185 occur. The default method simply returns ``True``, indicating that by 186 default, all channels will be interested in read events. 187 188 189 .. method:: writable() 190 191 Called each time around the asynchronous loop to determine whether a 192 channel's socket should be added to the list on which write events can 193 occur. The default method simply returns ``True``, indicating that by 194 default, all channels will be interested in write events. 195 196 197 In addition, each channel delegates or extends many of the socket methods. 198 Most of these are nearly identical to their socket partners. 199 200 201 .. method:: create_socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 202 203 This is identical to the creation of a normal socket, and will use the 204 same options for creation. Refer to the :mod:`socket` documentation for 205 information on creating sockets. 206 207 .. versionchanged:: 3.3 208 *family* and *type* arguments can be omitted. 209 210 211 .. method:: connect(address) 212 213 As with the normal socket object, *address* is a tuple with the first 214 element the host to connect to, and the second the port number. 215 216 217 .. method:: send(data) 218 219 Send *data* to the remote end-point of the socket. 220 221 222 .. method:: recv(buffer_size) 223 224 Read at most *buffer_size* bytes from the socket's remote end-point. An 225 empty bytes object implies that the channel has been closed from the 226 other end. 227 228 Note that :meth:`recv` may raise :exc:`BlockingIOError` , even though 229 :func:`select.select` or :func:`select.poll` has reported the socket 230 ready for reading. 231 232 233 .. method:: listen(backlog) 234 235 Listen for connections made to the socket. The *backlog* argument 236 specifies the maximum number of queued connections and should be at least 237 1; the maximum value is system-dependent (usually 5). 238 239 240 .. method:: bind(address) 241 242 Bind the socket to *address*. The socket must not already be bound. (The 243 format of *address* depends on the address family --- refer to the 244 :mod:`socket` documentation for more information.) To mark 245 the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call 246 the :class:`dispatcher` object's :meth:`set_reuse_addr` method. 247 248 249 .. method:: accept() 250 251 Accept a connection. The socket must be bound to an address and listening 252 for connections. The return value can be either ``None`` or a pair 253 ``(conn, address)`` where *conn* is a *new* socket object usable to send 254 and receive data on the connection, and *address* is the address bound to 255 the socket on the other end of the connection. 256 When ``None`` is returned it means the connection didn't take place, in 257 which case the server should just ignore this event and keep listening 258 for further incoming connections. 259 260 261 .. method:: close() 262 263 Close the socket. All future operations on the socket object will fail. 264 The remote end-point will receive no more data (after queued data is 265 flushed). Sockets are automatically closed when they are 266 garbage-collected. 267 268 269.. class:: dispatcher_with_send() 270 271 A :class:`dispatcher` subclass which adds simple buffered output capability, 272 useful for simple clients. For more sophisticated usage use 273 :class:`asynchat.async_chat`. 274 275.. class:: file_dispatcher() 276 277 A file_dispatcher takes a file descriptor or :term:`file object` along 278 with an optional map argument and wraps it for use with the :c:func:`poll` 279 or :c:func:`loop` functions. If provided a file object or anything with a 280 :c:func:`fileno` method, that method will be called and passed to the 281 :class:`file_wrapper` constructor. 282 283 .. availability:: Unix. 284 285.. class:: file_wrapper() 286 287 A file_wrapper takes an integer file descriptor and calls :func:`os.dup` to 288 duplicate the handle so that the original handle may be closed independently 289 of the file_wrapper. This class implements sufficient methods to emulate a 290 socket for use by the :class:`file_dispatcher` class. 291 292 .. availability:: Unix. 293 294 295.. _asyncore-example-1: 296 297asyncore Example basic HTTP client 298---------------------------------- 299 300Here is a very basic HTTP client that uses the :class:`dispatcher` class to 301implement its socket handling:: 302 303 import asyncore 304 305 class HTTPClient(asyncore.dispatcher): 306 307 def __init__(self, host, path): 308 asyncore.dispatcher.__init__(self) 309 self.create_socket() 310 self.connect( (host, 80) ) 311 self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' % 312 (path, host), 'ascii') 313 314 def handle_connect(self): 315 pass 316 317 def handle_close(self): 318 self.close() 319 320 def handle_read(self): 321 print(self.recv(8192)) 322 323 def writable(self): 324 return (len(self.buffer) > 0) 325 326 def handle_write(self): 327 sent = self.send(self.buffer) 328 self.buffer = self.buffer[sent:] 329 330 331 client = HTTPClient('www.python.org', '/') 332 asyncore.loop() 333 334.. _asyncore-example-2: 335 336asyncore Example basic echo server 337---------------------------------- 338 339Here is a basic echo server that uses the :class:`dispatcher` class to accept 340connections and dispatches the incoming connections to a handler:: 341 342 import asyncore 343 344 class EchoHandler(asyncore.dispatcher_with_send): 345 346 def handle_read(self): 347 data = self.recv(8192) 348 if data: 349 self.send(data) 350 351 class EchoServer(asyncore.dispatcher): 352 353 def __init__(self, host, port): 354 asyncore.dispatcher.__init__(self) 355 self.create_socket() 356 self.set_reuse_addr() 357 self.bind((host, port)) 358 self.listen(5) 359 360 def handle_accepted(self, sock, addr): 361 print('Incoming connection from %s' % repr(addr)) 362 handler = EchoHandler(sock) 363 364 server = EchoServer('localhost', 8080) 365 asyncore.loop() 366