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