blob: 8f8be9888aec316adb49e224612247d97ed0ed42 [file] [log] [blame]
Fred Drake7d807791999-07-02 14:25:03 +00001\section{\module{asyncore} ---
Fred Drake38e5d272000-04-03 20:13:55 +00002 Asynchronous socket handler}
Fred Drake7d807791999-07-02 14:25:03 +00003
4\declaremodule{builtin}{asyncore}
Fred Drake38e5d272000-04-03 20:13:55 +00005\modulesynopsis{A base class for developing asynchronous socket
Fred Drake7d807791999-07-02 14:25:03 +00006 handling services.}
7\moduleauthor{Sam Rushing}{rushing@nightmare.com}
8\sectionauthor{Christopher Petrilli}{petrilli@amber.org}
9% Heavily adapted from original documentation by Sam Rushing.
10
Fred Drake38e5d272000-04-03 20:13:55 +000011This module provides the basic infrastructure for writing asynchronous
Fred Drake7d807791999-07-02 14:25:03 +000012socket service clients and servers.
13
Fred Drake7d807791999-07-02 14:25:03 +000014There are only two ways to have a program on a single processor do
15``more than one thing at a time.'' Multi-threaded programming is the
16simplest and most popular way to do it, but there is another very
Fred Drake6166b871999-07-06 21:00:18 +000017different technique, that lets you have nearly all the advantages of
Fred Draked5dfe981999-07-06 15:50:23 +000018multi-threading, without actually using multiple threads. It's really
Fred Drake7d807791999-07-02 14:25:03 +000019only practical if your program is largely I/O bound. If your program
Fred Drake8ee679f2001-07-14 02:50:55 +000020is processor bound, then pre-emptive scheduled threads are probably what
21you really need. Network servers are rarely processor bound, however.
Fred Drake7d807791999-07-02 14:25:03 +000022
23If your operating system supports the \cfunction{select()} system call
24in its I/O library (and nearly all do), then you can use it to juggle
25multiple communication channels at once; doing other work while your
26I/O is taking place in the ``background.'' Although this strategy can
27seem strange and complex, especially at first, it is in many ways
28easier to understand and control than multi-threaded programming.
Fred Draked5dfe981999-07-06 15:50:23 +000029The module documented here solves many of the difficult problems for
Fred Drake7d807791999-07-02 14:25:03 +000030you, making the task of building sophisticated high-performance
31network servers and clients a snap.
32
33\begin{classdesc}{dispatcher}{}
34 The first class we will introduce is the \class{dispatcher} class.
35 This is a thin wrapper around a low-level socket object. To make
36 it more useful, it has a few methods for event-handling on it.
37 Otherwise, it can be treated as a normal non-blocking socket object.
38
39 The direct interface between the select loop and the socket object
40 are the \method{handle_read_event()} and
41 \method{handle_write_event()} methods. These are called whenever an
42 object `fires' that event.
43
44 The firing of these low-level events can tell us whether certain
45 higher-level events have taken place, depending on the timing and
46 the state of the connection. For example, if we have asked for a
47 socket to connect to another host, we know that the connection has
48 been made when the socket fires a write event (at this point you
49 know that you may write to it with the expectation of success).
50 The implied higher-level events are:
51
52 \begin{tableii}{l|l}{code}{Event}{Description}
53 \lineii{handle_connect()}{Implied by a write event}
54 \lineii{handle_close()}{Implied by a read event with no data available}
55 \lineii{handle_accept()}{Implied by a read event on a listening socket}
56 \end{tableii}
57\end{classdesc}
58
Fred Draked7616622001-12-05 21:37:50 +000059\begin{funcdesc}{loop}{\optional{timeout\optional{, use_poll\optional{,
60 map}}}}
61 Enter a polling loop that only terminates after all open channels
62 have been closed. All arguments are optional. The \var{timeout}
63 argument sets the timeout parameter for the appropriate
64 \function{select()} or \function{poll()} call, measured in seconds;
65 the default is 30 seconds. The \var{use_poll} parameter, if true,
66 indicates that \function{poll()} should be used in preference to
67 \function{select()} (the default is false). The \var{map} parameter
68 is a dictionary that gives a list of channels to watch. As channels
69 are closed they are deleted from their map. If \var{map} is
70 omitted, a global map is used.
71\end{funcdesc}
72
Fred Drake7d807791999-07-02 14:25:03 +000073This set of user-level events is larger than the basics. The
74full set of methods that can be overridden in your subclass are:
75
76\begin{methoddesc}{handle_read}{}
77 Called when there is new data to be read from a socket.
78\end{methoddesc}
79
80\begin{methoddesc}{handle_write}{}
81 Called when there is an attempt to write data to the object.
82 Often this method will implement the necessary buffering for
83 performance. For example:
84
85\begin{verbatim}
86def handle_write(self):
87 sent = self.send(self.buffer)
88 self.buffer = self.buffer[sent:]
89\end{verbatim}
90\end{methoddesc}
91
92\begin{methoddesc}{handle_expt}{}
93 Called when there is out of band (OOB) data for a socket
94 connection. This will almost never happen, as OOB is
95 tenuously supported and rarely used.
96\end{methoddesc}
97
98\begin{methoddesc}{handle_connect}{}
99 Called when the socket actually makes a connection. This
100 might be used to send a ``welcome'' banner, or something
101 similar.
102\end{methoddesc}
103
104\begin{methoddesc}{handle_close}{}
105 Called when the socket is closed.
106\end{methoddesc}
107
108\begin{methoddesc}{handle_accept}{}
109 Called on listening sockets when they actually accept a new
110 connection.
111\end{methoddesc}
112
113\begin{methoddesc}{readable}{}
114 Each time through the \method{select()} loop, the set of sockets
115 is scanned, and this method is called to see if there is any
116 interest in reading. The default method simply returns \code{1},
117 indicating that by default, all channels will be interested.
118\end{methoddesc}
119
Fred Drake19647ca2000-11-01 03:12:34 +0000120\begin{methoddesc}{writable}{}
Fred Drake7d807791999-07-02 14:25:03 +0000121 Each time through the \method{select()} loop, the set of sockets
122 is scanned, and this method is called to see if there is any
123 interest in writing. The default method simply returns \code{1},
Thomas Woutersf8316632000-07-16 19:01:10 +0000124 indicating that by default, all channels will be interested.
Fred Drake7d807791999-07-02 14:25:03 +0000125\end{methoddesc}
126
127In addition, there are the basic methods needed to construct and
128manipulate ``channels,'' which are what we will call the socket
129connections in this context. Note that most of these are nearly
Fred Draked5dfe981999-07-06 15:50:23 +0000130identical to their socket partners.
Fred Drake7d807791999-07-02 14:25:03 +0000131
132\begin{methoddesc}{create_socket}{family, type}
133 This is identical to the creation of a normal socket, and
Fred Draked5dfe981999-07-06 15:50:23 +0000134 will use the same options for creation. Refer to the
135 \refmodule{socket} documentation for information on creating
136 sockets.
Fred Drake7d807791999-07-02 14:25:03 +0000137\end{methoddesc}
138
139\begin{methoddesc}{connect}{address}
Fred Draked5dfe981999-07-06 15:50:23 +0000140 As with the normal socket object, \var{address} is a
Fred Drake7d807791999-07-02 14:25:03 +0000141 tuple with the first element the host to connect to, and the
142 second the port.
143\end{methoddesc}
144
145\begin{methoddesc}{send}{data}
146 Send \var{data} out the socket.
147\end{methoddesc}
148
149\begin{methoddesc}{recv}{buffer_size}
150 Read at most \var{buffer_size} bytes from the socket.
151\end{methoddesc}
152
Fred Drakec80d4dd2001-05-29 15:37:45 +0000153\begin{methoddesc}{listen}{backlog}
Fred Drake7d807791999-07-02 14:25:03 +0000154 Listen for connections made to the socket. The \var{backlog}
155 argument specifies the maximum number of queued connections
156 and should be at least 1; the maximum value is
157 system-dependent (usually 5).
158\end{methoddesc}
159
160\begin{methoddesc}{bind}{address}
161 Bind the socket to \var{address}. The socket must not already
162 be bound. (The format of \var{address} depends on the address
163 family --- see above.)
164\end{methoddesc}
165
166\begin{methoddesc}{accept}{}
167 Accept a connection. The socket must be bound to an address
168 and listening for connections. The return value is a pair
169 \code{(\var{conn}, \var{address})} where \var{conn} is a
170 \emph{new} socket object usable to send and receive data on
171 the connection, and \var{address} is the address bound to the
172 socket on the other end of the connection.
173\end{methoddesc}
174
175\begin{methoddesc}{close}{}
176 Close the socket. All future operations on the socket object
177 will fail. The remote end will receive no more data (after
178 queued data is flushed). Sockets are automatically closed
179 when they are garbage-collected.
180\end{methoddesc}
181
182
183\subsection{Example basic HTTP client \label{asyncore-example}}
184
185As a basic example, below is a very basic HTTP client that uses the
186\class{dispatcher} class to implement its socket handling:
187
188\begin{verbatim}
189class http_client(asyncore.dispatcher):
190 def __init__(self, host,path):
191 asyncore.dispatcher.__init__(self)
192 self.path = path
193 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
194 self.connect( (host, 80) )
Fred Drake819815a2001-04-09 15:57:06 +0000195 self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % self.path
Fred Drake7d807791999-07-02 14:25:03 +0000196
197 def handle_connect(self):
198 pass
199
200 def handle_read(self):
201 data = self.recv(8192)
202 print data
203
Fred Drake19647ca2000-11-01 03:12:34 +0000204 def writable(self):
Fred Drake7d807791999-07-02 14:25:03 +0000205 return (len(self.buffer) > 0)
206
207 def handle_write(self):
208 sent = self.send(self.buffer)
209 self.buffer = self.buffer[sent:]
210\end{verbatim}