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