• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`SocketServer` --- A framework for network servers
2=======================================================
3
4.. module:: SocketServer
5   :synopsis: A framework for network servers.
6
7.. note::
8
9   The :mod:`SocketServer` module has been renamed to :mod:`socketserver` in
10   Python 3.  The :term:`2to3` tool will automatically adapt imports when
11   converting your sources to Python 3.
12
13**Source code:** :source:`Lib/SocketServer.py`
14
15--------------
16
17The :mod:`SocketServer` module simplifies the task of writing network servers.
18
19There are four basic concrete server classes:
20
21
22.. class:: TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
23
24   This uses the Internet TCP protocol, which provides for
25   continuous streams of data between the client and server.
26   If *bind_and_activate* is true, the constructor automatically attempts to
27   invoke :meth:`~BaseServer.server_bind` and
28   :meth:`~BaseServer.server_activate`.  The other parameters are passed to
29   the :class:`BaseServer` base class.
30
31
32.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
33
34   This uses datagrams, which are discrete packets of information that may
35   arrive out of order or be lost while in transit.  The parameters are
36   the same as for :class:`TCPServer`.
37
38
39.. class:: UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
40           UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)
41
42   These more infrequently used classes are similar to the TCP and
43   UDP classes, but use Unix domain sockets; they're not available on
44   non-Unix platforms.  The parameters are the same as for
45   :class:`TCPServer`.
46
47
48These four classes process requests :dfn:`synchronously`; each request must be
49completed before the next request can be started.  This isn't suitable if each
50request takes a long time to complete, because it requires a lot of computation,
51or because it returns a lot of data which the client is slow to process.  The
52solution is to create a separate process or thread to handle each request; the
53:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes can be used to
54support asynchronous behaviour.
55
56Creating a server requires several steps.  First, you must create a request
57handler class by subclassing the :class:`BaseRequestHandler` class and
58overriding its :meth:`~BaseRequestHandler.handle` method;
59this method will process incoming
60requests.  Second, you must instantiate one of the server classes, passing it
61the server's address and the request handler class.  Then call the
62:meth:`~BaseServer.handle_request` or
63:meth:`~BaseServer.serve_forever` method of the server object to
64process one or many requests.  Finally, call :meth:`~BaseServer.server_close`
65to close the socket.
66
67When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
68you should explicitly declare how you want your threads to behave on an abrupt
69shutdown. The :class:`ThreadingMixIn` class defines an attribute
70*daemon_threads*, which indicates whether or not the server should wait for
71thread termination. You should set the flag explicitly if you would like threads
72to behave autonomously; the default is :const:`False`, meaning that Python will
73not exit until all threads created by :class:`ThreadingMixIn` have exited.
74
75Server classes have the same external methods and attributes, no matter what
76network protocol they use.
77
78
79Server Creation Notes
80---------------------
81
82There are five classes in an inheritance diagram, four of which represent
83synchronous servers of four types::
84
85   +------------+
86   | BaseServer |
87   +------------+
88         |
89         v
90   +-----------+        +------------------+
91   | TCPServer |------->| UnixStreamServer |
92   +-----------+        +------------------+
93         |
94         v
95   +-----------+        +--------------------+
96   | UDPServer |------->| UnixDatagramServer |
97   +-----------+        +--------------------+
98
99Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
100:class:`UnixStreamServer` --- the only difference between an IP and a Unix
101stream server is the address family, which is simply repeated in both Unix
102server classes.
103
104
105.. class:: ForkingMixIn
106           ThreadingMixIn
107
108   Forking and threading versions of each type of server can be created
109   using these mix-in classes.  For instance, :class:`ThreadingUDPServer`
110   is created as follows::
111
112      class ThreadingUDPServer(ThreadingMixIn, UDPServer):
113          pass
114
115   The mix-in class comes first, since it overrides a method defined in
116   :class:`UDPServer`.  Setting the various attributes also changes the
117   behavior of the underlying server mechanism.
118
119   :class:`ForkingMixIn` and the Forking classes mentioned below are
120   only available on POSIX platforms that support :func:`~os.fork`.
121
122
123.. class:: ForkingTCPServer
124           ForkingUDPServer
125           ThreadingTCPServer
126           ThreadingUDPServer
127
128   These classes are pre-defined using the mix-in classes.
129
130
131To implement a service, you must derive a class from :class:`BaseRequestHandler`
132and redefine its :meth:`~BaseRequestHandler.handle` method.
133You can then run various versions of
134the service by combining one of the server classes with your request handler
135class.  The request handler class must be different for datagram or stream
136services.  This can be hidden by using the handler subclasses
137:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
138
139Of course, you still have to use your head!  For instance, it makes no sense to
140use a forking server if the service contains state in memory that can be
141modified by different requests, since the modifications in the child process
142would never reach the initial state kept in the parent process and passed to
143each child.  In this case, you can use a threading server, but you will probably
144have to use locks to protect the integrity of the shared data.
145
146On the other hand, if you are building an HTTP server where all data is stored
147externally (for instance, in the file system), a synchronous class will
148essentially render the service "deaf" while one request is being handled --
149which may be for a very long time if a client is slow to receive all the data it
150has requested.  Here a threading or forking server is appropriate.
151
152In some cases, it may be appropriate to process part of a request synchronously,
153but to finish processing in a forked child depending on the request data.  This
154can be implemented by using a synchronous server and doing an explicit fork in
155the request handler class :meth:`~BaseRequestHandler.handle` method.
156
157Another approach to handling multiple simultaneous requests in an environment
158that supports neither threads nor :func:`~os.fork` (or where these are too
159expensive or inappropriate for the service) is to maintain an explicit table of
160partially finished requests and to use :func:`~select.select` to decide which
161request to work on next (or whether to handle a new incoming request).  This is
162particularly important for stream services where each client can potentially be
163connected for a long time (if threads or subprocesses cannot be used). See
164:mod:`asyncore` for another way to manage this.
165
166.. XXX should data and methods be intermingled, or separate?
167   how should the distinction between class and instance variables be drawn?
168
169
170Server Objects
171--------------
172
173.. class:: BaseServer(server_address, RequestHandlerClass)
174
175   This is the superclass of all Server objects in the module.  It defines the
176   interface, given below, but does not implement most of the methods, which is
177   done in subclasses.  The two parameters are stored in the respective
178   :attr:`server_address` and :attr:`RequestHandlerClass` attributes.
179
180
181   .. method:: fileno()
182
183      Return an integer file descriptor for the socket on which the server is
184      listening.  This function is most commonly passed to :func:`select.select`, to
185      allow monitoring multiple servers in the same process.
186
187
188   .. method:: handle_request()
189
190      Process a single request.  This function calls the following methods in
191      order: :meth:`get_request`, :meth:`verify_request`, and
192      :meth:`process_request`.  If the user-provided
193      :meth:`~BaseRequestHandler.handle` method of the
194      handler class raises an exception, the server's :meth:`handle_error` method
195      will be called.  If no request is received within :attr:`timeout`
196      seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
197      will return.
198
199
200   .. method:: serve_forever(poll_interval=0.5)
201
202      Handle requests until an explicit :meth:`shutdown` request.  Poll for
203      shutdown every *poll_interval* seconds.
204      Ignores the :attr:`timeout` attribute.
205      If you need to do periodic tasks, do them in another thread.
206
207
208   .. method:: shutdown()
209
210      Tell the :meth:`serve_forever` loop to stop and wait until it does.
211
212      .. versionadded:: 2.6
213
214
215   .. method:: server_close()
216
217      Clean up the server. May be overridden.
218
219      .. versionadded:: 2.6
220
221
222   .. attribute:: address_family
223
224      The family of protocols to which the server's socket belongs.
225      Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
226
227
228   .. attribute:: RequestHandlerClass
229
230      The user-provided request handler class; an instance of this class is created
231      for each request.
232
233
234   .. attribute:: server_address
235
236      The address on which the server is listening.  The format of addresses varies
237      depending on the protocol family;
238      see the documentation for the :mod:`socket` module
239      for details.  For Internet protocols, this is a tuple containing a string giving
240      the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
241
242
243   .. attribute:: socket
244
245      The socket object on which the server will listen for incoming requests.
246
247
248   The server classes support the following class variables:
249
250   .. XXX should class variables be covered before instance variables, or vice versa?
251
252   .. attribute:: allow_reuse_address
253
254      Whether the server will allow the reuse of an address. This defaults to
255      :const:`False`, and can be set in subclasses to change the policy.
256
257
258   .. attribute:: request_queue_size
259
260      The size of the request queue.  If it takes a long time to process a single
261      request, any requests that arrive while the server is busy are placed into a
262      queue, up to :attr:`request_queue_size` requests.  Once the queue is full,
263      further requests from clients will get a "Connection denied" error.  The default
264      value is usually 5, but this can be overridden by subclasses.
265
266
267   .. attribute:: socket_type
268
269      The type of socket used by the server; :const:`socket.SOCK_STREAM` and
270      :const:`socket.SOCK_DGRAM` are two common values.
271
272
273   .. attribute:: timeout
274
275      Timeout duration, measured in seconds, or :const:`None` if no timeout is
276      desired.  If :meth:`handle_request` receives no incoming requests within the
277      timeout period, the :meth:`handle_timeout` method is called.
278
279
280   There are various server methods that can be overridden by subclasses of base
281   server classes like :class:`TCPServer`; these methods aren't useful to external
282   users of the server object.
283
284   .. XXX should the default implementations of these be documented, or should
285      it be assumed that the user will look at SocketServer.py?
286
287   .. method:: finish_request()
288
289      Actually processes the request by instantiating :attr:`RequestHandlerClass` and
290      calling its :meth:`~BaseRequestHandler.handle` method.
291
292
293   .. method:: get_request()
294
295      Must accept a request from the socket, and return a 2-tuple containing the *new*
296      socket object to be used to communicate with the client, and the client's
297      address.
298
299
300   .. method:: handle_error(request, client_address)
301
302      This function is called if the :meth:`~BaseRequestHandler.handle`
303      method of a :attr:`RequestHandlerClass` instance raises
304      an exception.  The default action is to print the traceback to
305      standard output and continue handling further requests.
306
307
308   .. method:: handle_timeout()
309
310      This function is called when the :attr:`timeout` attribute has been set to a
311      value other than :const:`None` and the timeout period has passed with no
312      requests being received.  The default action for forking servers is
313      to collect the status of any child processes that have exited, while
314      in threading servers this method does nothing.
315
316
317   .. method:: process_request(request, client_address)
318
319      Calls :meth:`finish_request` to create an instance of the
320      :attr:`RequestHandlerClass`.  If desired, this function can create a new process
321      or thread to handle the request; the :class:`ForkingMixIn` and
322      :class:`ThreadingMixIn` classes do this.
323
324
325   .. Is there any point in documenting the following two functions?
326      What would the purpose of overriding them be: initializing server
327      instance variables, adding new network families?
328
329   .. method:: server_activate()
330
331      Called by the server's constructor to activate the server.  The default behavior
332      for a TCP server just invokes :meth:`~socket.socket.listen`
333      on the server's socket. May be overridden.
334
335
336   .. method:: server_bind()
337
338      Called by the server's constructor to bind the socket to the desired address.
339      May be overridden.
340
341
342   .. method:: verify_request(request, client_address)
343
344      Must return a Boolean value; if the value is :const:`True`, the request will be
345      processed, and if it's :const:`False`, the request will be denied. This function
346      can be overridden to implement access controls for a server. The default
347      implementation always returns :const:`True`.
348
349
350Request Handler Objects
351-----------------------
352
353.. class:: BaseRequestHandler
354
355   This is the superclass of all request handler objects.  It defines
356   the interface, given below.  A concrete request handler subclass must
357   define a new :meth:`handle` method, and can override any of
358   the other methods.  A new instance of the subclass is created for each
359   request.
360
361
362   .. method:: setup()
363
364      Called before the :meth:`handle` method to perform any initialization actions
365      required.  The default implementation does nothing.
366
367
368   .. method:: handle()
369
370      This function must do all the work required to service a request.  The
371      default implementation does nothing.  Several instance attributes are
372      available to it; the request is available as :attr:`self.request`; the client
373      address as :attr:`self.client_address`; and the server instance as
374      :attr:`self.server`, in case it needs access to per-server information.
375
376      The type of :attr:`self.request` is different for datagram or stream
377      services.  For stream services, :attr:`self.request` is a socket object; for
378      datagram services, :attr:`self.request` is a pair of string and socket.
379
380
381   .. method:: finish()
382
383      Called after the :meth:`handle` method to perform any clean-up actions
384      required.  The default implementation does nothing.  If :meth:`setup`
385      raises an exception, this function will not be called.
386
387
388.. class:: StreamRequestHandler
389           DatagramRequestHandler
390
391   These :class:`BaseRequestHandler` subclasses override the
392   :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish`
393   methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes.
394   The :attr:`self.rfile` and :attr:`self.wfile` attributes can be
395   read or written, respectively, to get the request data or return data
396   to the client.
397
398
399Examples
400--------
401
402:class:`SocketServer.TCPServer` Example
403~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
404
405This is the server side::
406
407   import SocketServer
408
409   class MyTCPHandler(SocketServer.BaseRequestHandler):
410       """
411       The request handler class for our server.
412
413       It is instantiated once per connection to the server, and must
414       override the handle() method to implement communication to the
415       client.
416       """
417
418       def handle(self):
419           # self.request is the TCP socket connected to the client
420           self.data = self.request.recv(1024).strip()
421           print "{} wrote:".format(self.client_address[0])
422           print self.data
423           # just send back the same data, but upper-cased
424           self.request.sendall(self.data.upper())
425
426   if __name__ == "__main__":
427       HOST, PORT = "localhost", 9999
428
429       # Create the server, binding to localhost on port 9999
430       server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
431
432       # Activate the server; this will keep running until you
433       # interrupt the program with Ctrl-C
434       server.serve_forever()
435
436An alternative request handler class that makes use of streams (file-like
437objects that simplify communication by providing the standard file interface)::
438
439   class MyTCPHandler(SocketServer.StreamRequestHandler):
440
441       def handle(self):
442           # self.rfile is a file-like object created by the handler;
443           # we can now use e.g. readline() instead of raw recv() calls
444           self.data = self.rfile.readline().strip()
445           print "{} wrote:".format(self.client_address[0])
446           print self.data
447           # Likewise, self.wfile is a file-like object used to write back
448           # to the client
449           self.wfile.write(self.data.upper())
450
451The difference is that the ``readline()`` call in the second handler will call
452``recv()`` multiple times until it encounters a newline character, while the
453single ``recv()`` call in the first handler will just return what has been sent
454from the client in one ``sendall()`` call.
455
456
457This is the client side::
458
459   import socket
460   import sys
461
462   HOST, PORT = "localhost", 9999
463   data = " ".join(sys.argv[1:])
464
465   # Create a socket (SOCK_STREAM means a TCP socket)
466   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
467
468   try:
469       # Connect to server and send data
470       sock.connect((HOST, PORT))
471       sock.sendall(data + "\n")
472
473       # Receive data from the server and shut down
474       received = sock.recv(1024)
475   finally:
476       sock.close()
477
478   print "Sent:     {}".format(data)
479   print "Received: {}".format(received)
480
481
482The output of the example should look something like this:
483
484Server:
485
486.. code-block:: shell-session
487
488   $ python TCPServer.py
489   127.0.0.1 wrote:
490   hello world with TCP
491   127.0.0.1 wrote:
492   python is nice
493
494Client:
495
496.. code-block:: shell-session
497
498   $ python TCPClient.py hello world with TCP
499   Sent:     hello world with TCP
500   Received: HELLO WORLD WITH TCP
501   $ python TCPClient.py python is nice
502   Sent:     python is nice
503   Received: PYTHON IS NICE
504
505
506:class:`SocketServer.UDPServer` Example
507~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
508
509This is the server side::
510
511   import SocketServer
512
513   class MyUDPHandler(SocketServer.BaseRequestHandler):
514       """
515       This class works similar to the TCP handler class, except that
516       self.request consists of a pair of data and client socket, and since
517       there is no connection the client address must be given explicitly
518       when sending data back via sendto().
519       """
520
521       def handle(self):
522           data = self.request[0].strip()
523           socket = self.request[1]
524           print "{} wrote:".format(self.client_address[0])
525           print data
526           socket.sendto(data.upper(), self.client_address)
527
528   if __name__ == "__main__":
529       HOST, PORT = "localhost", 9999
530       server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
531       server.serve_forever()
532
533This is the client side::
534
535   import socket
536   import sys
537
538   HOST, PORT = "localhost", 9999
539   data = " ".join(sys.argv[1:])
540
541   # SOCK_DGRAM is the socket type to use for UDP sockets
542   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
543
544   # As you can see, there is no connect() call; UDP has no connections.
545   # Instead, data is directly sent to the recipient via sendto().
546   sock.sendto(data + "\n", (HOST, PORT))
547   received = sock.recv(1024)
548
549   print "Sent:     {}".format(data)
550   print "Received: {}".format(received)
551
552The output of the example should look exactly like for the TCP server example.
553
554
555Asynchronous Mixins
556~~~~~~~~~~~~~~~~~~~
557
558To build asynchronous handlers, use the :class:`ThreadingMixIn` and
559:class:`ForkingMixIn` classes.
560
561An example for the :class:`ThreadingMixIn` class::
562
563   import socket
564   import threading
565   import SocketServer
566
567   class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
568
569       def handle(self):
570           data = self.request.recv(1024)
571           cur_thread = threading.current_thread()
572           response = "{}: {}".format(cur_thread.name, data)
573           self.request.sendall(response)
574
575   class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
576       pass
577
578   def client(ip, port, message):
579       sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
580       sock.connect((ip, port))
581       try:
582           sock.sendall(message)
583           response = sock.recv(1024)
584           print "Received: {}".format(response)
585       finally:
586           sock.close()
587
588   if __name__ == "__main__":
589       # Port 0 means to select an arbitrary unused port
590       HOST, PORT = "localhost", 0
591
592       server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
593       ip, port = server.server_address
594
595       # Start a thread with the server -- that thread will then start one
596       # more thread for each request
597       server_thread = threading.Thread(target=server.serve_forever)
598       # Exit the server thread when the main thread terminates
599       server_thread.daemon = True
600       server_thread.start()
601       print "Server loop running in thread:", server_thread.name
602
603       client(ip, port, "Hello World 1")
604       client(ip, port, "Hello World 2")
605       client(ip, port, "Hello World 3")
606
607       server.shutdown()
608       server.server_close()
609
610
611The output of the example should look something like this:
612
613.. code-block:: shell-session
614
615   $ python ThreadedTCPServer.py
616   Server loop running in thread: Thread-1
617   Received: Thread-2: Hello World 1
618   Received: Thread-3: Hello World 2
619   Received: Thread-4: Hello World 3
620
621
622The :class:`ForkingMixIn` class is used in the same way, except that the server
623will spawn a new process for each request.
624Available only on POSIX platforms that support :func:`~os.fork`.
625