blob: 11d36163e44a790a48d4291fb5ce4f696984bbab [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`asyncore` --- Asynchronous socket handler
2===============================================
3
4.. module:: asyncore
Georg Brandl9afde1c2007-11-01 20:32:30 +00005 :synopsis: A base class for developing asynchronous socket handling
6 services.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007
Georg Brandl116aa622007-08-15 14:28:22 +00008.. moduleauthor:: Sam Rushing <rushing@nightmare.com>
9.. sectionauthor:: Christopher Petrilli <petrilli@amber.org>
10.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
Christian Heimes5b5e81c2007-12-31 16:14:33 +000011.. heavily adapted from original documentation by Sam Rushing
Georg Brandl116aa622007-08-15 14:28:22 +000012
Raymond Hettingeread49752011-01-24 16:28:06 +000013**Source code:** :source:`Lib/asyncore.py`
14
Guido van Rossum16591f42016-10-25 08:49:13 -070015.. deprecated:: 3.6
16 Please use :mod:`asyncio` instead.
17
Raymond Hettingeread49752011-01-24 16:28:06 +000018--------------
Georg Brandl116aa622007-08-15 14:28:22 +000019
Guido van Rossum4da459c2013-11-22 12:27:45 -080020.. note::
21
22 This module exists for backwards compatibility only. For new code we
23 recommend using :mod:`asyncio`.
Guido van Rossumaa407752013-11-22 11:57:35 -080024
Georg Brandl116aa622007-08-15 14:28:22 +000025This module provides the basic infrastructure for writing asynchronous socket
26service clients and servers.
27
Georg Brandl116aa622007-08-15 14:28:22 +000028There 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
Georg Brandl9afde1c2007-11-01 20:32:30 +000030popular way to do it, but there is another very different technique, that lets
Georg Brandl116aa622007-08-15 14:28:22 +000031you 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
Georg Brandl9afde1c2007-11-01 20:32:30 +000033bound. If your program is processor bound, then pre-emptive scheduled threads
34are probably what you really need. Network servers are rarely processor
35bound, however.
Georg Brandl116aa622007-08-15 14:28:22 +000036
Georg Brandl60203b42010-10-06 10:11:56 +000037If your operating system supports the :c:func:`select` system call in its I/O
Georg Brandl116aa622007-08-15 14:28:22 +000038library (and nearly all do), then you can use it to juggle multiple
Georg Brandl9afde1c2007-11-01 20:32:30 +000039communication 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.
Georg Brandl116aa622007-08-15 14:28:22 +000047
Georg Brandl9afde1c2007-11-01 20:32:30 +000048The 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*.
Georg Brandl116aa622007-08-15 14:28:22 +000053
54Once the initial channel(s) is(are) created, calling the :func:`loop` function
Georg Brandl9afde1c2007-11-01 20:32:30 +000055activates channel service, which continues until the last channel (including
56any that have been added to the map during asynchronous service) is closed.
Georg Brandl116aa622007-08-15 14:28:22 +000057
58
59.. function:: loop([timeout[, use_poll[, map[,count]]]])
60
Georg Brandl9afde1c2007-11-01 20:32:30 +000061 Enter a polling loop that terminates after count passes or all open
62 channels have been closed. All arguments are optional. The *count*
Serhiy Storchakaecf41da2016-10-19 16:29:26 +030063 parameter defaults to ``None``, resulting in the loop terminating only when all
Georg Brandl9afde1c2007-11-01 20:32:30 +000064 channels have been closed. The *timeout* argument sets the timeout
Serhiy Storchakabfdcd432013-10-13 23:09:14 +030065 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``).
Georg Brandl116aa622007-08-15 14:28:22 +000069
Georg Brandl9afde1c2007-11-01 20:32:30 +000070 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.
Georg Brandl116aa622007-08-15 14:28:22 +000075
76
77.. class:: dispatcher()
78
79 The :class:`dispatcher` class is a thin wrapper around a low-level socket
Georg Brandl9afde1c2007-11-01 20:32:30 +000080 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.
Georg Brandl116aa622007-08-15 14:28:22 +000083
Georg Brandl9afde1c2007-11-01 20:32:30 +000084 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:
Georg Brandl116aa622007-08-15 14:28:22 +000091
92 +----------------------+----------------------------------------+
93 | Event | Description |
94 +======================+========================================+
R. David Murray78532ba2009-04-12 15:35:44 +000095 | ``handle_connect()`` | Implied by the first read or write |
96 | | event |
Georg Brandl116aa622007-08-15 14:28:22 +000097 +----------------------+----------------------------------------+
98 | ``handle_close()`` | Implied by a read event with no data |
99 | | available |
100 +----------------------+----------------------------------------+
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000101 | ``handle_accepted()``| Implied by a read event on a listening |
Georg Brandl116aa622007-08-15 14:28:22 +0000102 | | 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
Georg Brandl60203b42010-10-06 10:11:56 +0000107 should be added to the list of channels :c:func:`select`\ ed or
108 :c:func:`poll`\ ed for read and write events.
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Benjamin Petersone41251e2008-04-25 01:59:09 +0000110 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:
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
Benjamin Petersone41251e2008-04-25 01:59:09 +0000114 .. method:: handle_read()
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Benjamin Petersone41251e2008-04-25 01:59:09 +0000116 Called when the asynchronous loop detects that a :meth:`read` call on the
117 channel's socket will succeed.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119
Benjamin Petersone41251e2008-04-25 01:59:09 +0000120 .. method:: handle_write()
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Benjamin Petersone41251e2008-04-25 01:59:09 +0000122 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::
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Benjamin Petersone41251e2008-04-25 01:59:09 +0000126 def handle_write(self):
127 sent = self.send(self.buffer)
128 self.buffer = self.buffer[sent:]
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130
Benjamin Petersone41251e2008-04-25 01:59:09 +0000131 .. method:: handle_expt()
Georg Brandl116aa622007-08-15 14:28:22 +0000132
Benjamin Petersone41251e2008-04-25 01:59:09 +0000133 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136
Benjamin Petersone41251e2008-04-25 01:59:09 +0000137 .. method:: handle_connect()
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Benjamin Petersone41251e2008-04-25 01:59:09 +0000139 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143
Benjamin Petersone41251e2008-04-25 01:59:09 +0000144 .. method:: handle_close()
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Benjamin Petersone41251e2008-04-25 01:59:09 +0000146 Called when the socket is closed.
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148
Benjamin Petersone41251e2008-04-25 01:59:09 +0000149 .. method:: handle_error()
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Benjamin Petersone41251e2008-04-25 01:59:09 +0000151 Called when an exception is raised and not otherwise handled. The default
152 version prints a condensed traceback.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154
Benjamin Petersone41251e2008-04-25 01:59:09 +0000155 .. method:: handle_accept()
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Benjamin Petersone41251e2008-04-25 01:59:09 +0000157 Called on listening channels (passive openers) when a connection can be
158 established with a new remote endpoint that has issued a :meth:`connect`
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000159 call for the local endpoint. Deprecated in version 3.2; use
160 :meth:`handle_accepted` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Georg Brandleeed9552010-10-05 07:16:01 +0000162 .. deprecated:: 3.2
163
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000164
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`
Senthil Kumaran656df5e2011-06-19 18:22:33 -0700169 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
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000171 bound to the socket on the other end of the connection.
172
Georg Brandleeed9552010-10-05 07:16:01 +0000173 .. versionadded:: 3.2
174
Georg Brandl116aa622007-08-15 14:28:22 +0000175
Benjamin Petersone41251e2008-04-25 01:59:09 +0000176 .. method:: readable()
Georg Brandl116aa622007-08-15 14:28:22 +0000177
Benjamin Petersone41251e2008-04-25 01:59:09 +0000178 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183
Benjamin Petersone41251e2008-04-25 01:59:09 +0000184 .. method:: writable()
Georg Brandl116aa622007-08-15 14:28:22 +0000185
Benjamin Petersone41251e2008-04-25 01:59:09 +0000186 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191
Benjamin Petersone41251e2008-04-25 01:59:09 +0000192 In addition, each channel delegates or extends many of the socket methods.
193 Most of these are nearly identical to their socket partners.
Georg Brandl116aa622007-08-15 14:28:22 +0000194
195
Giampaolo Rodolà103a6d62011-02-25 22:21:22 +0000196 .. method:: create_socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Benjamin Petersone41251e2008-04-25 01:59:09 +0000198 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Georg Brandlf5a1d762012-03-09 12:22:12 +0100202 .. versionchanged:: 3.3
203 *family* and *type* arguments can be omitted.
Giampaolo Rodolà103a6d62011-02-25 22:21:22 +0000204
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Benjamin Petersone41251e2008-04-25 01:59:09 +0000206 .. method:: connect(address)
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Benjamin Petersone41251e2008-04-25 01:59:09 +0000208 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211
Benjamin Petersone41251e2008-04-25 01:59:09 +0000212 .. method:: send(data)
Georg Brandl116aa622007-08-15 14:28:22 +0000213
Benjamin Petersone41251e2008-04-25 01:59:09 +0000214 Send *data* to the remote end-point of the socket.
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216
Benjamin Petersone41251e2008-04-25 01:59:09 +0000217 .. method:: recv(buffer_size)
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Benjamin Petersone41251e2008-04-25 01:59:09 +0000219 Read at most *buffer_size* bytes from the socket's remote end-point. An
Serhiy Storchaka5e028ae2014-02-06 21:10:41 +0200220 empty bytes object implies that the channel has been closed from the
221 other end.
Georg Brandl116aa622007-08-15 14:28:22 +0000222
Victor Stinner45cff662014-07-24 18:49:36 +0200223 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
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Benjamin Petersone41251e2008-04-25 01:59:09 +0000228 .. method:: listen(backlog)
Georg Brandl116aa622007-08-15 14:28:22 +0000229
Benjamin Petersone41251e2008-04-25 01:59:09 +0000230 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).
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234
Benjamin Petersone41251e2008-04-25 01:59:09 +0000235 .. method:: bind(address)
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Benjamin Petersone41251e2008-04-25 01:59:09 +0000237 Bind the socket to *address*. The socket must not already be bound. (The
Benjamin Peterson21896a32010-03-21 22:03:03 +0000238 format of *address* depends on the address family --- refer to the
239 :mod:`socket` documentation for more information.) To mark
Benjamin Petersone41251e2008-04-25 01:59:09 +0000240 the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call
241 the :class:`dispatcher` object's :meth:`set_reuse_addr` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243
Benjamin Petersone41251e2008-04-25 01:59:09 +0000244 .. method:: accept()
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Benjamin Petersone41251e2008-04-25 01:59:09 +0000246 Accept a connection. The socket must be bound to an address and listening
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000247 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.
Benjamin Petersone41251e2008-04-25 01:59:09 +0000254
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.
Georg Brandl116aa622007-08-15 14:28:22 +0000262
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000263
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
Josiah Carlsond74900e2008-07-07 04:15:08 +0000270.. class:: file_dispatcher()
271
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000272 A file_dispatcher takes a file descriptor or :term:`file object` along
Georg Brandl60203b42010-10-06 10:11:56 +0000273 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
Josiah Carlsond74900e2008-07-07 04:15:08 +0000276 :class:`file_wrapper` constructor. Availability: UNIX.
277
278.. class:: file_wrapper()
279
280 A file_wrapper takes an integer file descriptor and calls :func:`os.dup` to
281 duplicate the handle so that the original handle may be closed independently
282 of the file_wrapper. This class implements sufficient methods to emulate a
283 socket for use by the :class:`file_dispatcher` class. Availability: UNIX.
284
Georg Brandl116aa622007-08-15 14:28:22 +0000285
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000286.. _asyncore-example-1:
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288asyncore Example basic HTTP client
289----------------------------------
290
291Here is a very basic HTTP client that uses the :class:`dispatcher` class to
292implement its socket handling::
293
Giampaolo Rodola'0fb41b52012-05-15 15:46:00 +0200294 import asyncore
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000296 class HTTPClient(asyncore.dispatcher):
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298 def __init__(self, host, path):
299 asyncore.dispatcher.__init__(self)
Giampaolo Rodolà103a6d62011-02-25 22:21:22 +0000300 self.create_socket()
Georg Brandl116aa622007-08-15 14:28:22 +0000301 self.connect( (host, 80) )
Georg Brandl45ec3332011-03-06 11:05:03 +0100302 self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
303 (path, host), 'ascii')
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305 def handle_connect(self):
306 pass
307
308 def handle_close(self):
309 self.close()
310
311 def handle_read(self):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000312 print(self.recv(8192))
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314 def writable(self):
315 return (len(self.buffer) > 0)
316
317 def handle_write(self):
318 sent = self.send(self.buffer)
319 self.buffer = self.buffer[sent:]
320
Georg Brandl116aa622007-08-15 14:28:22 +0000321
Serhiy Storchakadba90392016-05-10 12:01:23 +0300322 client = HTTPClient('www.python.org', '/')
323 asyncore.loop()
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000324
325.. _asyncore-example-2:
326
327asyncore Example basic echo server
328----------------------------------
329
Giampaolo Rodolà61a0bf52011-02-25 14:50:57 +0000330Here is a basic echo server that uses the :class:`dispatcher` class to accept
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000331connections and dispatches the incoming connections to a handler::
332
333 import asyncore
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000334
335 class EchoHandler(asyncore.dispatcher_with_send):
336
337 def handle_read(self):
338 data = self.recv(8192)
Giampaolo Rodolà61a0bf52011-02-25 14:50:57 +0000339 if data:
340 self.send(data)
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000341
342 class EchoServer(asyncore.dispatcher):
343
344 def __init__(self, host, port):
345 asyncore.dispatcher.__init__(self)
Giampaolo Rodolà103a6d62011-02-25 22:21:22 +0000346 self.create_socket()
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000347 self.set_reuse_addr()
348 self.bind((host, port))
349 self.listen(5)
350
351 def handle_accepted(self, sock, addr):
352 print('Incoming connection from %s' % repr(addr))
353 handler = EchoHandler(sock)
354
355 server = EchoServer('localhost', 8080)
356 asyncore.loop()