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