blob: 51cab5ee8602f9c54175887f2b95103f8ff0fb72 [file] [log] [blame]
Georg Brandle152a772008-05-24 18:31:28 +00001
2:mod:`SocketServer` --- A framework for network servers
Georg Brandl8ec7f652007-08-15 14:28:01 +00003=======================================================
4
Georg Brandl7a148c22008-05-12 10:03:16 +00005.. module:: SocketServer
Georg Brandl8ec7f652007-08-15 14:28:01 +00006 :synopsis: A framework for network servers.
Georg Brandl7a148c22008-05-12 10:03:16 +00007
8.. note::
Georg Brandle152a772008-05-24 18:31:28 +00009
10 The :mod:`SocketServer` module has been renamed to `socketserver` in Python
11 3.0. The :term:`2to3` tool will automatically adapt imports when converting
12 your sources to 3.0.
Alexandre Vassalottifea23a42008-05-12 02:18:15 +000013
Georg Brandl8ec7f652007-08-15 14:28:01 +000014
Georg Brandle152a772008-05-24 18:31:28 +000015The :mod:`SocketServer` module simplifies the task of writing network servers.
Georg Brandl8ec7f652007-08-15 14:28:01 +000016
17There are four basic server classes: :class:`TCPServer` uses the Internet TCP
18protocol, which provides for continuous streams of data between the client and
19server. :class:`UDPServer` uses datagrams, which are discrete packets of
20information that may arrive out of order or be lost while in transit. The more
21infrequently used :class:`UnixStreamServer` and :class:`UnixDatagramServer`
22classes are similar, but use Unix domain sockets; they're not available on
23non-Unix platforms. For more details on network programming, consult a book
24such as
25W. Richard Steven's UNIX Network Programming or Ralph Davis's Win32 Network
26Programming.
27
28These four classes process requests :dfn:`synchronously`; each request must be
29completed before the next request can be started. This isn't suitable if each
30request takes a long time to complete, because it requires a lot of computation,
31or because it returns a lot of data which the client is slow to process. The
32solution is to create a separate process or thread to handle each request; the
33:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes can be used to
34support asynchronous behaviour.
35
36Creating a server requires several steps. First, you must create a request
37handler class by subclassing the :class:`BaseRequestHandler` class and
38overriding its :meth:`handle` method; this method will process incoming
39requests. Second, you must instantiate one of the server classes, passing it
40the server's address and the request handler class. Finally, call the
41:meth:`handle_request` or :meth:`serve_forever` method of the server object to
42process one or many requests.
43
44When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
45you should explicitly declare how you want your threads to behave on an abrupt
46shutdown. The :class:`ThreadingMixIn` class defines an attribute
47*daemon_threads*, which indicates whether or not the server should wait for
48thread termination. You should set the flag explicitly if you would like threads
49to behave autonomously; the default is :const:`False`, meaning that Python will
50not exit until all threads created by :class:`ThreadingMixIn` have exited.
51
52Server classes have the same external methods and attributes, no matter what
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +000053network protocol they use.
Georg Brandl8ec7f652007-08-15 14:28:01 +000054
55
56Server Creation Notes
57---------------------
58
59There are five classes in an inheritance diagram, four of which represent
60synchronous servers of four types::
61
62 +------------+
63 | BaseServer |
64 +------------+
65 |
66 v
67 +-----------+ +------------------+
68 | TCPServer |------->| UnixStreamServer |
69 +-----------+ +------------------+
70 |
71 v
72 +-----------+ +--------------------+
73 | UDPServer |------->| UnixDatagramServer |
74 +-----------+ +--------------------+
75
76Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
77:class:`UnixStreamServer` --- the only difference between an IP and a Unix
78stream server is the address family, which is simply repeated in both Unix
79server classes.
80
81Forking and threading versions of each type of server can be created using the
82:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes. For instance,
83a threading UDP server class is created as follows::
84
85 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
86
87The mix-in class must come first, since it overrides a method defined in
88:class:`UDPServer`. Setting the various member variables also changes the
89behavior of the underlying server mechanism.
90
91To implement a service, you must derive a class from :class:`BaseRequestHandler`
92and redefine its :meth:`handle` method. You can then run various versions of
93the service by combining one of the server classes with your request handler
94class. The request handler class must be different for datagram or stream
95services. This can be hidden by using the handler subclasses
96:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
97
98Of course, you still have to use your head! For instance, it makes no sense to
99use a forking server if the service contains state in memory that can be
100modified by different requests, since the modifications in the child process
101would never reach the initial state kept in the parent process and passed to
102each child. In this case, you can use a threading server, but you will probably
103have to use locks to protect the integrity of the shared data.
104
105On the other hand, if you are building an HTTP server where all data is stored
106externally (for instance, in the file system), a synchronous class will
107essentially render the service "deaf" while one request is being handled --
108which may be for a very long time if a client is slow to receive all the data it
109has requested. Here a threading or forking server is appropriate.
110
111In some cases, it may be appropriate to process part of a request synchronously,
112but to finish processing in a forked child depending on the request data. This
113can be implemented by using a synchronous server and doing an explicit fork in
114the request handler class :meth:`handle` method.
115
116Another approach to handling multiple simultaneous requests in an environment
117that supports neither threads nor :func:`fork` (or where these are too expensive
118or inappropriate for the service) is to maintain an explicit table of partially
119finished requests and to use :func:`select` to decide which request to work on
120next (or whether to handle a new incoming request). This is particularly
121important for stream services where each client can potentially be connected for
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000122a long time (if threads or subprocesses cannot be used). See :mod:`asyncore` for
123another way to manage this.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000124
Georg Brandlb19be572007-12-29 10:57:00 +0000125.. XXX should data and methods be intermingled, or separate?
126 how should the distinction between class and instance variables be drawn?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
128
129Server Objects
130--------------
131
132
133.. function:: fileno()
134
135 Return an integer file descriptor for the socket on which the server is
136 listening. This function is most commonly passed to :func:`select.select`, to
137 allow monitoring multiple servers in the same process.
138
139
140.. function:: handle_request()
141
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000142 Process a single request. This function calls the following methods in
143 order: :meth:`get_request`, :meth:`verify_request`, and
144 :meth:`process_request`. If the user-provided :meth:`handle` method of the
145 handler class raises an exception, the server's :meth:`handle_error` method
146 will be called. If no request is received within :attr:`self.timeout`
147 seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
148 will return.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
150
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000151.. function:: serve_forever(poll_interval=0.5)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000153 Handle requests until an explicit :meth:`shutdown` request. Polls for
154 shutdown every *poll_interval* seconds.
155
156
157.. function:: shutdown()
158
159 Tells the :meth:`serve_forever` loop to stop and waits until it does.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
161
162.. data:: address_family
163
164 The family of protocols to which the server's socket belongs.
Georg Brandl0aaf5592008-05-11 10:59:39 +0000165 Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000166
167
168.. data:: RequestHandlerClass
169
170 The user-provided request handler class; an instance of this class is created
171 for each request.
172
173
174.. data:: server_address
175
176 The address on which the server is listening. The format of addresses varies
177 depending on the protocol family; see the documentation for the socket module
178 for details. For Internet protocols, this is a tuple containing a string giving
179 the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
180
181
182.. data:: socket
183
184 The socket object on which the server will listen for incoming requests.
185
186The server classes support the following class variables:
187
Georg Brandlb19be572007-12-29 10:57:00 +0000188.. XXX should class variables be covered before instance variables, or vice versa?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189
190
191.. data:: allow_reuse_address
192
193 Whether the server will allow the reuse of an address. This defaults to
194 :const:`False`, and can be set in subclasses to change the policy.
195
196
197.. data:: request_queue_size
198
199 The size of the request queue. If it takes a long time to process a single
200 request, any requests that arrive while the server is busy are placed into a
201 queue, up to :attr:`request_queue_size` requests. Once the queue is full,
202 further requests from clients will get a "Connection denied" error. The default
203 value is usually 5, but this can be overridden by subclasses.
204
205
206.. data:: socket_type
207
208 The type of socket used by the server; :const:`socket.SOCK_STREAM` and
Georg Brandl0aaf5592008-05-11 10:59:39 +0000209 :const:`socket.SOCK_DGRAM` are two common values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000210
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000211.. data:: timeout
212
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000213 Timeout duration, measured in seconds, or :const:`None` if no timeout is
214 desired. If :meth:`handle_request` receives no incoming requests within the
215 timeout period, the :meth:`handle_timeout` method is called.
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000216
Georg Brandl8ec7f652007-08-15 14:28:01 +0000217There are various server methods that can be overridden by subclasses of base
218server classes like :class:`TCPServer`; these methods aren't useful to external
219users of the server object.
220
Georg Brandlb19be572007-12-29 10:57:00 +0000221.. XXX should the default implementations of these be documented, or should
Georg Brandle152a772008-05-24 18:31:28 +0000222 it be assumed that the user will look at SocketServer.py?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223
224
225.. function:: finish_request()
226
227 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
228 calling its :meth:`handle` method.
229
230
231.. function:: get_request()
232
233 Must accept a request from the socket, and return a 2-tuple containing the *new*
234 socket object to be used to communicate with the client, and the client's
235 address.
236
237
238.. function:: handle_error(request, client_address)
239
240 This function is called if the :attr:`RequestHandlerClass`'s :meth:`handle`
241 method raises an exception. The default action is to print the traceback to
242 standard output and continue handling further requests.
243
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000244.. function:: handle_timeout()
245
Georg Brandl67d69332008-05-18 08:52:59 +0000246 This function is called when the :attr:`timeout` attribute has been set to a
247 value other than :const:`None` and the timeout period has passed with no
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000248 requests being received. The default action for forking servers is
249 to collect the status of any child processes that have exited, while
250 in threading servers this method does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251
252.. function:: process_request(request, client_address)
253
254 Calls :meth:`finish_request` to create an instance of the
255 :attr:`RequestHandlerClass`. If desired, this function can create a new process
256 or thread to handle the request; the :class:`ForkingMixIn` and
257 :class:`ThreadingMixIn` classes do this.
258
Georg Brandlb19be572007-12-29 10:57:00 +0000259.. Is there any point in documenting the following two functions?
260 What would the purpose of overriding them be: initializing server
261 instance variables, adding new network families?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000262
263
264.. function:: server_activate()
265
266 Called by the server's constructor to activate the server. The default behavior
267 just :meth:`listen`\ s to the server's socket. May be overridden.
268
269
270.. function:: server_bind()
271
272 Called by the server's constructor to bind the socket to the desired address.
273 May be overridden.
274
275
276.. function:: verify_request(request, client_address)
277
278 Must return a Boolean value; if the value is :const:`True`, the request will be
279 processed, and if it's :const:`False`, the request will be denied. This function
280 can be overridden to implement access controls for a server. The default
281 implementation always returns :const:`True`.
282
283
284RequestHandler Objects
285----------------------
286
287The request handler class must define a new :meth:`handle` method, and can
288override any of the following methods. A new instance is created for each
289request.
290
291
292.. function:: finish()
293
Georg Brandl67d69332008-05-18 08:52:59 +0000294 Called after the :meth:`handle` method to perform any clean-up actions
295 required. The default implementation does nothing. If :meth:`setup` or
296 :meth:`handle` raise an exception, this function will not be called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000297
298
299.. function:: handle()
300
Georg Brandl67d69332008-05-18 08:52:59 +0000301 This function must do all the work required to service a request. The
302 default implementation does nothing. Several instance attributes are
303 available to it; the request is available as :attr:`self.request`; the client
304 address as :attr:`self.client_address`; and the server instance as
305 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306
Georg Brandl67d69332008-05-18 08:52:59 +0000307 The type of :attr:`self.request` is different for datagram or stream
308 services. For stream services, :attr:`self.request` is a socket object; for
309 datagram services, :attr:`self.request` is a pair of string and socket.
310 However, this can be hidden by using the request handler subclasses
311 :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which
312 override the :meth:`setup` and :meth:`finish` methods, and provide
313 :attr:`self.rfile` and :attr:`self.wfile` attributes. :attr:`self.rfile` and
314 :attr:`self.wfile` can be read or written, respectively, to get the request
315 data or return data to the client.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316
317
318.. function:: setup()
319
320 Called before the :meth:`handle` method to perform any initialization actions
321 required. The default implementation does nothing.
322
Georg Brandl67d69332008-05-18 08:52:59 +0000323
324Examples
325--------
326
Georg Brandle152a772008-05-24 18:31:28 +0000327:class:`SocketServer.TCPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000328~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
329
330This is the server side::
331
Georg Brandle152a772008-05-24 18:31:28 +0000332 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000333
Georg Brandle152a772008-05-24 18:31:28 +0000334 class MyTCPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000335 """
336 The RequestHandler class for our server.
337
338 It is instantiated once per connection to the server, and must
339 override the handle() method to implement communication to the
340 client.
341 """
342
343 def handle(self):
344 # self.request is the TCP socket connected to the client
345 self.data = self.request.recv(1024).strip()
346 print "%s wrote:" % self.client_address[0]
347 print self.data
348 # just send back the same data, but upper-cased
349 self.request.send(self.data.upper())
350
351 if __name__ == "__main__":
352 HOST, PORT = "localhost", 9999
353
354 # Create the server, binding to localhost on port 9999
Georg Brandle152a772008-05-24 18:31:28 +0000355 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
Georg Brandl67d69332008-05-18 08:52:59 +0000356
357 # Activate the server; this will keep running until you
358 # interrupt the program with Ctrl-C
359 server.serve_forever()
360
361An alternative request handler class that makes use of streams (file-like
362objects that simplify communication by providing the standard file interface)::
363
Georg Brandle152a772008-05-24 18:31:28 +0000364 class MyTCPHandler(SocketServer.StreamRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000365
366 def handle(self):
367 # self.rfile is a file-like object created by the handler;
368 # we can now use e.g. readline() instead of raw recv() calls
369 self.data = self.rfile.readline().strip()
370 print "%s wrote:" % self.client_address[0]
371 print self.data
372 # Likewise, self.wfile is a file-like object used to write back
373 # to the client
374 self.wfile.write(self.data.upper())
375
376The difference is that the ``readline()`` call in the second handler will call
377``recv()`` multiple times until it encounters a newline character, while the
378single ``recv()`` call in the first handler will just return what has been sent
379from the client in one ``send()`` call.
380
381
382This is the client side::
383
384 import socket
385 import sys
386
387 HOST, PORT = "localhost", 9999
388 data = " ".join(sys.argv[1:])
389
390 # Create a socket (SOCK_STREAM means a TCP socket)
391 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
392
393 # Connect to server and send data
394 sock.connect((HOST, PORT))
395 sock.send(data + "\n")
396
397 # Receive data from the server and shut down
398 received = sock.recv(1024)
399 sock.close()
400
401 print "Sent: %s" % data
402 print "Received: %s" % received
403
404
405The output of the example should look something like this:
406
407Server::
408
409 $ python TCPServer.py
410 127.0.0.1 wrote:
411 hello world with TCP
412 127.0.0.1 wrote:
413 python is nice
414
415Client::
416
417 $ python TCPClient.py hello world with TCP
418 Sent: hello world with TCP
419 Received: HELLO WORLD WITH TCP
420 $ python TCPClient.py python is nice
421 Sent: python is nice
422 Received: PYTHON IS NICE
423
424
Georg Brandle152a772008-05-24 18:31:28 +0000425:class:`SocketServer.UDPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000426~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
427
428This is the server side::
429
Georg Brandle152a772008-05-24 18:31:28 +0000430 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000431
Georg Brandle152a772008-05-24 18:31:28 +0000432 class MyUDPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000433 """
434 This class works similar to the TCP handler class, except that
435 self.request consists of a pair of data and client socket, and since
436 there is no connection the client address must be given explicitly
437 when sending data back via sendto().
438 """
439
440 def handle(self):
441 data = self.request[0].strip()
442 socket = self.request[1]
443 print "%s wrote:" % self.client_address[0]
444 print data
445 socket.sendto(data.upper(), self.client_address)
446
447 if __name__ == "__main__":
448 HOST, PORT = "localhost", 9999
Georg Brandle152a772008-05-24 18:31:28 +0000449 server = SocketServer.UDPServer((HOST, PORT), BaseUDPRequestHandler)
Georg Brandl67d69332008-05-18 08:52:59 +0000450 server.serve_forever()
451
452This is the client side::
453
454 import socket
455 import sys
456
457 HOST, PORT = "localhost"
458 data = " ".join(sys.argv[1:])
459
460 # SOCK_DGRAM is the socket type to use for UDP sockets
461 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
462
463 # As you can see, there is no connect() call; UDP has no connections.
464 # Instead, data is directly sent to the recipient via sendto().
465 sock.sendto(data + "\n", (HOST, PORT))
466 received = sock.recv(1024)
467
468 print "Sent: %s" % data
469 print "Received: %s" % received
470
471The output of the example should look exactly like for the TCP server example.
472
473
474Asynchronous Mixins
475~~~~~~~~~~~~~~~~~~~
476
477To build asynchronous handlers, use the :class:`ThreadingMixIn` and
478:class:`ForkingMixIn` classes.
479
480An example for the :class:`ThreadingMixIn` class::
481
482 import socket
483 import threading
Georg Brandle152a772008-05-24 18:31:28 +0000484 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000485
Georg Brandle152a772008-05-24 18:31:28 +0000486 class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000487
488 def handle(self):
489 data = self.request.recv(1024)
490 cur_thread = threading.currentThread()
491 response = "%s: %s" % (cur_thread.getName(), data)
492 self.request.send(response)
493
Georg Brandle152a772008-05-24 18:31:28 +0000494 class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
Georg Brandl67d69332008-05-18 08:52:59 +0000495 pass
496
497 def client(ip, port, message):
498 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
499 sock.connect((ip, port))
500 sock.send(message)
501 response = sock.recv(1024)
502 print "Received: %s" % response
503 sock.close()
504
505 if __name__ == "__main__":
506 # Port 0 means to select an arbitrary unused port
507 HOST, PORT = "localhost", 0
508
509 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
510 ip, port = server.server_address
511
512 # Start a thread with the server -- that thread will then start one
513 # more thread for each request
514 server_thread = threading.Thread(target=server.serve_forever)
515 # Exit the server thread when the main thread terminates
516 server_thread.setDaemon(True)
517 server_thread.start()
518 print "Server loop running in thread:", t.getName()
519
520 client(ip, port, "Hello World 1")
521 client(ip, port, "Hello World 2")
522 client(ip, port, "Hello World 3")
523
524 server.shutdown()
525
526The output of the example should look something like this::
527
528 $ python ThreadedTCPServer.py
529 Server loop running in thread: Thread-1
530 Received: Thread-2: Hello World 1
531 Received: Thread-3: Hello World 2
532 Received: Thread-4: Hello World 3
533
534
535The :class:`ForkingMixIn` class is used in the same way, except that the server
536will spawn a new process for each request.