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