blob: b0cc4164ea62dc31408a6213b6933e4c494294c2 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{SocketServer} ---
Fred Drakef8ca7d82000-10-10 17:03:45 +00002 A framework for network servers}
Fred Drakeb91e9341998-07-23 17:59:49 +00003
Fred Drakef8ca7d82000-10-10 17:03:45 +00004\declaremodule{standard}{SocketServer}
Fred Drakeb91e9341998-07-23 17:59:49 +00005\modulesynopsis{A framework for network servers.}
6
Guido van Rossum6181e001997-05-19 19:55:16 +00007
Fred Drakebe2b6d71998-03-14 06:40:34 +00008The \module{SocketServer} module simplifies the task of writing network
Fred Drake0d3b4f81997-12-04 14:36:52 +00009servers.
Guido van Rossum6181e001997-05-19 19:55:16 +000010
Fred Drakebe2b6d71998-03-14 06:40:34 +000011There are four basic server classes: \class{TCPServer} uses the
Guido van Rossum6181e001997-05-19 19:55:16 +000012Internet TCP protocol, which provides for continuous streams of data
Fred Drakebe2b6d71998-03-14 06:40:34 +000013between the client and server. \class{UDPServer} uses datagrams, which
Guido van Rossum6181e001997-05-19 19:55:16 +000014are discrete packets of information that may arrive out of order or be
15lost while in transit. The more infrequently used
Fred Drakebe2b6d71998-03-14 06:40:34 +000016\class{UnixStreamServer} and \class{UnixDatagramServer} classes are
Fred Drakea8090641998-01-13 19:10:02 +000017similar, but use \UNIX{} domain sockets; they're not available on
18non-\UNIX{} platforms. For more details on network programming, consult
Fred Drake37f15741999-11-10 16:21:37 +000019a book such as W. Richard Steven's \citetitle{UNIX Network Programming}
20or Ralph Davis's \citetitle{Win32 Network Programming}.
Guido van Rossum6181e001997-05-19 19:55:16 +000021
22These four classes process requests \dfn{synchronously}; each request
23must be completed before the next request can be started. This isn't
24suitable if each request takes a long time to complete, because it
25requires a lot of computation, or because it returns a lot of data
26which the client is slow to process. The solution is to create a
27separate process or thread to handle each request; the
Fred Drakebe2b6d71998-03-14 06:40:34 +000028\class{ForkingMixIn} and \class{ThreadingMixIn} mix-in classes can be
Guido van Rossum6181e001997-05-19 19:55:16 +000029used to support asynchronous behaviour.
30
31Creating a server requires several steps. First, you must create a
Fred Drakebe2b6d71998-03-14 06:40:34 +000032request handler class by subclassing the \class{BaseRequestHandler}
33class and overriding its \method{handle()} method; this method will
Guido van Rossum6181e001997-05-19 19:55:16 +000034process incoming requests. Second, you must instantiate one of the
35server classes, passing it the server's address and the request
Fred Drakebe2b6d71998-03-14 06:40:34 +000036handler class. Finally, call the \method{handle_request()} or
37\method{serve_forever()} method of the server object to process one or
Guido van Rossum6181e001997-05-19 19:55:16 +000038many requests.
39
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +000040When inheriting from \class{ThreadingMixIn} for threaded connection
41behavior, you should explicitly declare how you want your threads
42to behave on an abrupt shutdown. The \class{ThreadingMixIn} class
43defines an attribute \var{daemon_threads}, which indicates whether
44or not the server should wait for thread termination. You should
45set the flag explicitly if you would like threads to behave
Fred Drakea191bef2002-11-22 14:29:42 +000046autonomously; the default is \constant{False}, meaning that Python
47will not exit until all threads created by \class{ThreadingMixIn} have
48exited.
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +000049
Guido van Rossum6181e001997-05-19 19:55:16 +000050Server classes have the same external methods and attributes, no
51matter what network protocol they use:
52
Fred Drake19479911998-02-13 06:58:54 +000053\setindexsubitem{(SocketServer protocol)}
Fred Drake798654f1997-11-30 05:53:22 +000054
Skip Montanaro766349e2005-05-12 13:42:42 +000055\subsection{Server Creation Notes}
56
57There are five classes in an inheritance diagram, four of which represent
58synchronous servers of four types:
59
60\begin{verbatim}
61 +------------+
62 | BaseServer |
63 +------------+
64 |
65 v
66 +-----------+ +------------------+
67 | TCPServer |------->| UnixStreamServer |
68 +-----------+ +------------------+
69 |
70 v
71 +-----------+ +--------------------+
72 | UDPServer |------->| UnixDatagramServer |
73 +-----------+ +--------------------+
74\end{verbatim}
75
76Note that \class{UnixDatagramServer} derives from \class{UDPServer}, not
77from \class{UnixStreamServer} -- the only difference between an IP and a
78Unix stream server is the address family, which is simply repeated in both
79unix server classes.
80
81Forking and threading versions of each type of server can be created using
82the \class{ForkingMixIn} and \class{ThreadingMixIn} mix-in classes. For
83instance, a threading UDP server class is created as follows:
84
85\begin{verbatim}
86 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
87\end{verbatim}
88
89The mix-in class must come first, since it overrides a method defined in
90\class{UDPServer}. Setting the various member variables also changes the
91behavior of the underlying server mechanism.
92
93To implement a service, you must derive a class from
94\class{BaseRequestHandler} and redefine its \method{handle()} method. You
95can then run various versions of the service by combining one of the server
96classes with your request handler class. The request handler class must be
97different for datagram or stream services. This can be hidden by using the
98mix-in request handler classes \class{StreamRequestHandler} or
99\class{DatagramRequestHandler}.
100
101Of course, you still have to use your head! For instance, it makes no sense
102to use a forking server if the service contains state in memory that can be
103modified by different requests, since the modifications in the child process
104would never reach the initial state kept in the parent process and passed to
105each child. In this case, you can use a threading server, but you will
106probably have to use locks to protect the integrity of the shared data.
107
108On the other hand, if you are building an HTTP server where all data is
109stored externally (for instance, in the file system), a synchronous class
110will essentially render the service "deaf" while one request is being
111handled -- which may be for a very long time if a client is slow to receive
112all the data it has requested. Here a threading or forking server is
113appropriate.
114
115In some cases, it may be appropriate to process part of a request
116synchronously, but to finish processing in a forked child depending on the
117request data. This can be implemented by using a synchronous server and
118doing an explicit fork in the request handler class \method{handle()}
119method.
120
121Another approach to handling multiple simultaneous requests in an
122environment that supports neither threads nor \function{fork()} (or where
123these are too expensive or inappropriate for the service) is to maintain an
124explicit table of partially finished requests and to use \function{select()}
125to decide which request to work on next (or whether to handle a new incoming
126request). This is particularly important for stream services where each
127client can potentially be connected for a long time (if threads or
128subprocesses cannot be used).
129
Guido van Rossum6181e001997-05-19 19:55:16 +0000130%XXX should data and methods be intermingled, or separate?
131% how should the distinction between class and instance variables be
132% drawn?
133
Skip Montanaro766349e2005-05-12 13:42:42 +0000134\subsection{Server Objects}
135
Guido van Rossum6181e001997-05-19 19:55:16 +0000136\begin{funcdesc}{fileno}{}
137Return an integer file descriptor for the socket on which the server
138is listening. This function is most commonly passed to
Fred Drakebe2b6d71998-03-14 06:40:34 +0000139\function{select.select()}, to allow monitoring multiple servers in the
Guido van Rossum6181e001997-05-19 19:55:16 +0000140same process.
141\end{funcdesc}
142
143\begin{funcdesc}{handle_request}{}
144Process a single request. This function calls the following methods
Fred Drakebe2b6d71998-03-14 06:40:34 +0000145in order: \method{get_request()}, \method{verify_request()}, and
146\method{process_request()}. If the user-provided \method{handle()}
147method of the handler class raises an exception, the server's
148\method{handle_error()} method will be called.
Guido van Rossum6181e001997-05-19 19:55:16 +0000149\end{funcdesc}
150
151\begin{funcdesc}{serve_forever}{}
152Handle an infinite number of requests. This simply calls
Fred Drakebe2b6d71998-03-14 06:40:34 +0000153\method{handle_request()} inside an infinite loop.
Guido van Rossum6181e001997-05-19 19:55:16 +0000154\end{funcdesc}
155
156\begin{datadesc}{address_family}
157The family of protocols to which the server's socket belongs.
Fred Drakebe2b6d71998-03-14 06:40:34 +0000158\constant{socket.AF_INET} and \constant{socket.AF_UNIX} are two
159possible values.
Guido van Rossum6181e001997-05-19 19:55:16 +0000160\end{datadesc}
161
162\begin{datadesc}{RequestHandlerClass}
163The user-provided request handler class; an instance of this class is
164created for each request.
165\end{datadesc}
166
167\begin{datadesc}{server_address}
168The address on which the server is listening. The format of addresses
169varies depending on the protocol family; see the documentation for the
170socket module for details. For Internet protocols, this is a tuple
171containing a string giving the address, and an integer port number:
172\code{('127.0.0.1', 80)}, for example.
173\end{datadesc}
174
175\begin{datadesc}{socket}
176The socket object on which the server will listen for incoming requests.
177\end{datadesc}
178
179% XXX should class variables be covered before instance variables, or
180% vice versa?
181
182The server classes support the following class variables:
183
Moshe Zadkadd802202000-12-13 20:39:22 +0000184\begin{datadesc}{allow_reuse_address}
185Whether the server will allow the reuse of an address. This defaults
Skip Montanarobf760752004-07-21 02:47:10 +0000186to \constant{False}, and can be set in subclasses to change the policy.
Moshe Zadkadd802202000-12-13 20:39:22 +0000187\end{datadesc}
188
Guido van Rossum6181e001997-05-19 19:55:16 +0000189\begin{datadesc}{request_queue_size}
190The size of the request queue. If it takes a long time to process a
191single request, any requests that arrive while the server is busy are
Fred Drakebe2b6d71998-03-14 06:40:34 +0000192placed into a queue, up to \member{request_queue_size} requests. Once
Guido van Rossum6181e001997-05-19 19:55:16 +0000193the queue is full, further requests from clients will get a
194``Connection denied'' error. The default value is usually 5, but this
195can be overridden by subclasses.
196\end{datadesc}
197
198\begin{datadesc}{socket_type}
Fred Drakebe2b6d71998-03-14 06:40:34 +0000199The type of socket used by the server; \constant{socket.SOCK_STREAM}
200and \constant{socket.SOCK_DGRAM} are two possible values.
Guido van Rossum6181e001997-05-19 19:55:16 +0000201\end{datadesc}
202
203There are various server methods that can be overridden by subclasses
Fred Drakebe2b6d71998-03-14 06:40:34 +0000204of base server classes like \class{TCPServer}; these methods aren't
Guido van Rossum6181e001997-05-19 19:55:16 +0000205useful to external users of the server object.
206
207% should the default implementations of these be documented, or should
208% it be assumed that the user will look at SocketServer.py?
209
210\begin{funcdesc}{finish_request}{}
211Actually processes the request by instantiating
Fred Drakebe2b6d71998-03-14 06:40:34 +0000212\member{RequestHandlerClass} and calling its \method{handle()} method.
Guido van Rossum6181e001997-05-19 19:55:16 +0000213\end{funcdesc}
214
215\begin{funcdesc}{get_request}{}
216Must accept a request from the socket, and return a 2-tuple containing
217the \emph{new} socket object to be used to communicate with the
218client, and the client's address.
219\end{funcdesc}
220
Fred Drakecce10901998-03-17 06:33:25 +0000221\begin{funcdesc}{handle_error}{request, client_address}
Fred Drakebe2b6d71998-03-14 06:40:34 +0000222This function is called if the \member{RequestHandlerClass}'s
223\method{handle()} method raises an exception. The default action is
224to print the traceback to standard output and continue handling
225further requests.
Guido van Rossum6181e001997-05-19 19:55:16 +0000226\end{funcdesc}
227
Fred Drakecce10901998-03-17 06:33:25 +0000228\begin{funcdesc}{process_request}{request, client_address}
Fred Drakebe2b6d71998-03-14 06:40:34 +0000229Calls \method{finish_request()} to create an instance of the
230\member{RequestHandlerClass}. If desired, this function can create a
231new process or thread to handle the request; the \class{ForkingMixIn}
232and \class{ThreadingMixIn} classes do this.
Guido van Rossum6181e001997-05-19 19:55:16 +0000233\end{funcdesc}
234
235% Is there any point in documenting the following two functions?
236% What would the purpose of overriding them be: initializing server
237% instance variables, adding new network families?
238
239\begin{funcdesc}{server_activate}{}
Skip Montanaro766349e2005-05-12 13:42:42 +0000240Called by the server's constructor to activate the server. The default
241behavior just \method{listen}s to the server's socket.
Guido van Rossum6181e001997-05-19 19:55:16 +0000242May be overridden.
243\end{funcdesc}
244
245\begin{funcdesc}{server_bind}{}
246Called by the server's constructor to bind the socket to the desired
247address. May be overridden.
248\end{funcdesc}
249
Fred Drakecce10901998-03-17 06:33:25 +0000250\begin{funcdesc}{verify_request}{request, client_address}
Skip Montanarobf760752004-07-21 02:47:10 +0000251Must return a Boolean value; if the value is \constant{True}, the request will be
252processed, and if it's \constant{False}, the request will be denied.
Guido van Rossum6181e001997-05-19 19:55:16 +0000253This function can be overridden to implement access controls for a server.
Skip Montanarobf760752004-07-21 02:47:10 +0000254The default implementation always returns \constant{True}.
Guido van Rossum6181e001997-05-19 19:55:16 +0000255\end{funcdesc}
256
Skip Montanaro766349e2005-05-12 13:42:42 +0000257\subsection{RequestHandler Objects}
258
Fred Drakebe2b6d71998-03-14 06:40:34 +0000259The request handler class must define a new \method{handle()} method,
260and can override any of the following methods. A new instance is
261created for each request.
Guido van Rossum6181e001997-05-19 19:55:16 +0000262
263\begin{funcdesc}{finish}{}
Fred Drakebe2b6d71998-03-14 06:40:34 +0000264Called after the \method{handle()} method to perform any clean-up
265actions required. The default implementation does nothing. If
266\method{setup()} or \method{handle()} raise an exception, this
267function will not be called.
Guido van Rossum6181e001997-05-19 19:55:16 +0000268\end{funcdesc}
269
270\begin{funcdesc}{handle}{}
271This function must do all the work required to service a request.
Skip Montanaro766349e2005-05-12 13:42:42 +0000272The default implementation does nothing.
Guido van Rossum6181e001997-05-19 19:55:16 +0000273Several instance attributes are available to it; the request is
Fred Drakebe2b6d71998-03-14 06:40:34 +0000274available as \member{self.request}; the client address as
Guido van Rossumda30f4c1998-11-16 19:07:04 +0000275\member{self.client_address}; and the server instance as
Fred Drakebe2b6d71998-03-14 06:40:34 +0000276\member{self.server}, in case it needs access to per-server
277information.
Guido van Rossum6181e001997-05-19 19:55:16 +0000278
Fred Drakebe2b6d71998-03-14 06:40:34 +0000279The type of \member{self.request} is different for datagram or stream
280services. For stream services, \member{self.request} is a socket
281object; for datagram services, \member{self.request} is a string.
Guido van Rossum6181e001997-05-19 19:55:16 +0000282However, this can be hidden by using the mix-in request handler
283classes
Fred Drakebe2b6d71998-03-14 06:40:34 +0000284\class{StreamRequestHandler} or \class{DatagramRequestHandler}, which
285override the \method{setup()} and \method{finish()} methods, and
286provides \member{self.rfile} and \member{self.wfile} attributes.
287\member{self.rfile} and \member{self.wfile} can be read or written,
288respectively, to get the request data or return data to the client.
Guido van Rossum6181e001997-05-19 19:55:16 +0000289\end{funcdesc}
290
291\begin{funcdesc}{setup}{}
Fred Drakebe2b6d71998-03-14 06:40:34 +0000292Called before the \method{handle()} method to perform any
293initialization actions required. The default implementation does
294nothing.
Guido van Rossum6181e001997-05-19 19:55:16 +0000295\end{funcdesc}