blob: aaaa61e9d9755c8425edc1fe4d50a018abdbee12 [file] [log] [blame]
Alexandre Vassalottice261952008-05-12 02:31:37 +00001:mod:`socketserver` --- A framework for network servers
Georg Brandl116aa622007-08-15 14:28:22 +00002=======================================================
3
Alexandre Vassalottice261952008-05-12 02:31:37 +00004.. module:: socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: A framework for network servers.
6
Raymond Hettinger469271d2011-01-27 20:38:46 +00007**Source code:** :source:`Lib/socketserver.py`
8
9--------------
10
Alexandre Vassalottice261952008-05-12 02:31:37 +000011The :mod:`socketserver` module simplifies the task of writing network servers.
Georg Brandl116aa622007-08-15 14:28:22 +000012
Martin Pantereac17b82016-02-19 03:27:46 +000013There 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 Brandl116aa622007-08-15 14:28:22 +000041
42These four classes process requests :dfn:`synchronously`; each request must be
43completed before the next request can be started. This isn't suitable if each
44request takes a long time to complete, because it requires a lot of computation,
45or because it returns a lot of data which the client is slow to process. The
46solution 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
48support asynchronous behaviour.
49
50Creating a server requires several steps. First, you must create a request
51handler class by subclassing the :class:`BaseRequestHandler` class and
Martin Pantereac17b82016-02-19 03:27:46 +000052overriding its :meth:`~BaseRequestHandler.handle` method;
53this method will process incoming
Georg Brandl116aa622007-08-15 14:28:22 +000054requests. Second, you must instantiate one of the server classes, passing it
Robert Collins1ee92832015-07-29 12:52:40 +120055the server's address and the request handler class. Then call the
Martin Pantereac17b82016-02-19 03:27:46 +000056:meth:`~BaseServer.handle_request` or
57:meth:`~BaseServer.serve_forever` method of the server object to
Robert Collins1ee92832015-07-29 12:52:40 +120058process one or many requests. Finally, call :meth:`~BaseServer.server_close`
59to close the socket.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
62you should explicitly declare how you want your threads to behave on an abrupt
Florent Xicluna599d76b2011-11-11 19:56:26 +010063shutdown. The :class:`ThreadingMixIn` class defines an attribute
Georg Brandl116aa622007-08-15 14:28:22 +000064*daemon_threads*, which indicates whether or not the server should wait for
Florent Xicluna599d76b2011-11-11 19:56:26 +010065thread termination. You should set the flag explicitly if you would like
66threads to behave autonomously; the default is :const:`False`, meaning that
67Python will not exit until all threads created by :class:`ThreadingMixIn` have
68exited.
Georg Brandl116aa622007-08-15 14:28:22 +000069
70Server classes have the same external methods and attributes, no matter what
Georg Brandlfceab5a2008-01-19 20:08:23 +000071network protocol they use.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73
74Server Creation Notes
75---------------------
76
77There are five classes in an inheritance diagram, four of which represent
78synchronous 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
94Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
95:class:`UnixStreamServer` --- the only difference between an IP and a Unix
96stream server is the address family, which is simply repeated in both Unix
97server classes.
98
Georg Brandl116aa622007-08-15 14:28:22 +000099
Martin Pantereac17b82016-02-19 03:27:46 +0000100.. class:: ForkingMixIn
101 ThreadingMixIn
Georg Brandl116aa622007-08-15 14:28:22 +0000102
Martin Pantereac17b82016-02-19 03:27:46 +0000103 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 Brandl116aa622007-08-15 14:28:22 +0000122
123To implement a service, you must derive a class from :class:`BaseRequestHandler`
Martin Pantereac17b82016-02-19 03:27:46 +0000124and redefine its :meth:`~BaseRequestHandler.handle` method.
125You can then run various versions of
Georg Brandl116aa622007-08-15 14:28:22 +0000126the service by combining one of the server classes with your request handler
127class. The request handler class must be different for datagram or stream
128services. This can be hidden by using the handler subclasses
129:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
130
131Of course, you still have to use your head! For instance, it makes no sense to
132use a forking server if the service contains state in memory that can be
133modified by different requests, since the modifications in the child process
134would never reach the initial state kept in the parent process and passed to
135each child. In this case, you can use a threading server, but you will probably
136have to use locks to protect the integrity of the shared data.
137
138On the other hand, if you are building an HTTP server where all data is stored
139externally (for instance, in the file system), a synchronous class will
140essentially render the service "deaf" while one request is being handled --
141which may be for a very long time if a client is slow to receive all the data it
142has requested. Here a threading or forking server is appropriate.
143
144In some cases, it may be appropriate to process part of a request synchronously,
145but to finish processing in a forked child depending on the request data. This
146can be implemented by using a synchronous server and doing an explicit fork in
Martin Pantereac17b82016-02-19 03:27:46 +0000147the request handler class :meth:`~BaseRequestHandler.handle` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149Another approach to handling multiple simultaneous requests in an environment
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300150that supports neither threads nor :func:`~os.fork` (or where these are too
151expensive or inappropriate for the service) is to maintain an explicit table of
Charles-François Natali1d29cc52014-03-24 22:25:39 +0000152partially finished requests and to use :mod:`selectors` to decide which
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300153request to work on next (or whether to handle a new incoming request). This is
154particularly important for stream services where each client can potentially be
155connected for a long time (if threads or subprocesses cannot be used). See
156:mod:`asyncore` for another way to manage this.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000158.. XXX should data and methods be intermingled, or separate?
159 how should the distinction between class and instance variables be drawn?
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161
162Server Objects
163--------------
164
Martin Pantereac17b82016-02-19 03:27:46 +0000165.. class:: BaseServer(server_address, RequestHandlerClass)
Georg Brandl116aa622007-08-15 14:28:22 +0000166
Benjamin Petersond23f8222009-04-05 19:13:16 +0000167 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 Pantereac17b82016-02-19 03:27:46 +0000169 done in subclasses. The two parameters are stored in the respective
170 :attr:`server_address` and :attr:`RequestHandlerClass` attributes.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000171
172
Martin Pantereac17b82016-02-19 03:27:46 +0000173 .. method:: fileno()
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Martin Pantereac17b82016-02-19 03:27:46 +0000175 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 Brandl116aa622007-08-15 14:28:22 +0000178
179
Martin Pantereac17b82016-02-19 03:27:46 +0000180 .. method:: handle_request()
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Martin Pantereac17b82016-02-19 03:27:46 +0000182 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 Brandl116aa622007-08-15 14:28:22 +0000190
191
Martin Pantereac17b82016-02-19 03:27:46 +0000192 .. method:: serve_forever(poll_interval=0.5)
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Martin Pantereac17b82016-02-19 03:27:46 +0000194 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 Heimesdd15f6c2008-03-16 00:07:10 +0000201
Martin Pantereac17b82016-02-19 03:27:46 +0000202 .. versionchanged:: 3.3
203 Added ``service_actions`` call to the ``serve_forever`` method.
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800204
205
Martin Pantereac17b82016-02-19 03:27:46 +0000206 .. method:: service_actions()
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800207
Martin Pantereac17b82016-02-19 03:27:46 +0000208 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 Kumaran5e826e82011-05-26 00:22:59 +0800211
Martin Pantereac17b82016-02-19 03:27:46 +0000212 .. versionadded:: 3.3
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000213
Martin Pantereac17b82016-02-19 03:27:46 +0000214 .. method:: shutdown()
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000215
Martin Pantereac17b82016-02-19 03:27:46 +0000216 Tell the :meth:`serve_forever` loop to stop and wait until it does.
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218
Martin Pantereac17b82016-02-19 03:27:46 +0000219 .. method:: server_close()
Robert Collins1ee92832015-07-29 12:52:40 +1200220
Martin Pantereac17b82016-02-19 03:27:46 +0000221 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 Collins1ee92832015-07-29 12:52:40 +1200228
Robert Collins1ee92832015-07-29 12:52:40 +1200229
Martin Pantereac17b82016-02-19 03:27:46 +0000230 .. attribute:: RequestHandlerClass
Robert Collins1ee92832015-07-29 12:52:40 +1200231
Martin Pantereac17b82016-02-19 03:27:46 +0000232 The user-provided request handler class; an instance of this class is created
233 for each request.
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Martin Pantereac17b82016-02-19 03:27:46 +0000236 .. attribute:: server_address
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Martin Pantereac17b82016-02-19 03:27:46 +0000238 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 Brandl116aa622007-08-15 14:28:22 +0000243
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Martin Pantereac17b82016-02-19 03:27:46 +0000245 .. attribute:: socket
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Martin Pantereac17b82016-02-19 03:27:46 +0000247 The socket object on which the server will listen for incoming requests.
Georg Brandl116aa622007-08-15 14:28:22 +0000248
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Martin Pantereac17b82016-02-19 03:27:46 +0000250 The server classes support the following class variables:
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Martin Pantereac17b82016-02-19 03:27:46 +0000252 .. XXX should class variables be covered before instance variables, or vice versa?
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Martin Pantereac17b82016-02-19 03:27:46 +0000254 .. attribute:: allow_reuse_address
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Martin Pantereac17b82016-02-19 03:27:46 +0000256 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 Petersond23f8222009-04-05 19:13:16 +0000258
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Martin Pantereac17b82016-02-19 03:27:46 +0000260 .. attribute:: request_queue_size
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Martin Pantereac17b82016-02-19 03:27:46 +0000262 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 Brandl116aa622007-08-15 14:28:22 +0000267
Georg Brandl116aa622007-08-15 14:28:22 +0000268
Martin Pantereac17b82016-02-19 03:27:46 +0000269 .. attribute:: socket_type
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Martin Pantereac17b82016-02-19 03:27:46 +0000271 The type of socket used by the server; :const:`socket.SOCK_STREAM` and
272 :const:`socket.SOCK_DGRAM` are two common values.
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Martin Pantereac17b82016-02-19 03:27:46 +0000275 .. attribute:: timeout
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Martin Pantereac17b82016-02-19 03:27:46 +0000277 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 Brandl116aa622007-08-15 14:28:22 +0000280
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Martin Pantereac17b82016-02-19 03:27:46 +0000282 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 Petersond23f8222009-04-05 19:13:16 +0000285
Martin Pantereac17b82016-02-19 03:27:46 +0000286 .. XXX should the default implementations of these be documented, or should
287 it be assumed that the user will look at socketserver.py?
Georg Brandlfceab5a2008-01-19 20:08:23 +0000288
Martin Pantereac17b82016-02-19 03:27:46 +0000289 .. method:: finish_request()
Georg Brandlfceab5a2008-01-19 20:08:23 +0000290
Martin Pantereac17b82016-02-19 03:27:46 +0000291 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
292 calling its :meth:`~BaseRequestHandler.handle` method.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000293
Georg Brandl116aa622007-08-15 14:28:22 +0000294
Martin Pantereac17b82016-02-19 03:27:46 +0000295 .. method:: get_request()
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Martin Pantereac17b82016-02-19 03:27:46 +0000297 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 Brandl116aa622007-08-15 14:28:22 +0000300
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Martin Pantereac17b82016-02-19 03:27:46 +0000302 .. method:: handle_error(request, client_address)
Georg Brandl116aa622007-08-15 14:28:22 +0000303
Martin Pantereac17b82016-02-19 03:27:46 +0000304 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
Martin Panterd9108d12016-02-21 08:49:56 +0000307 standard error and continue handling further requests.
308
309 .. versionchanged:: 3.6
310 Now only called for exceptions derived from the :exc:`Exception`
311 class.
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Martin Pantereac17b82016-02-19 03:27:46 +0000314 .. method:: handle_timeout()
Georg Brandl116aa622007-08-15 14:28:22 +0000315
Martin Pantereac17b82016-02-19 03:27:46 +0000316 This function is called when the :attr:`timeout` attribute has been set to a
317 value other than :const:`None` and the timeout period has passed with no
318 requests being received. The default action for forking servers is
319 to collect the status of any child processes that have exited, while
320 in threading servers this method does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000321
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Martin Pantereac17b82016-02-19 03:27:46 +0000323 .. method:: process_request(request, client_address)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000324
Martin Pantereac17b82016-02-19 03:27:46 +0000325 Calls :meth:`finish_request` to create an instance of the
326 :attr:`RequestHandlerClass`. If desired, this function can create a new process
327 or thread to handle the request; the :class:`ForkingMixIn` and
328 :class:`ThreadingMixIn` classes do this.
Georg Brandlfceab5a2008-01-19 20:08:23 +0000329
Georg Brandl116aa622007-08-15 14:28:22 +0000330
Martin Pantereac17b82016-02-19 03:27:46 +0000331 .. Is there any point in documenting the following two functions?
332 What would the purpose of overriding them be: initializing server
333 instance variables, adding new network families?
Benjamin Petersond23f8222009-04-05 19:13:16 +0000334
Martin Pantereac17b82016-02-19 03:27:46 +0000335 .. method:: server_activate()
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Martin Pantereac17b82016-02-19 03:27:46 +0000337 Called by the server's constructor to activate the server. The default behavior
338 for a TCP server just invokes :meth:`~socket.socket.listen`
339 on the server's socket. May be overridden.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Benjamin Petersond23f8222009-04-05 19:13:16 +0000341
Martin Pantereac17b82016-02-19 03:27:46 +0000342 .. method:: server_bind()
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Martin Pantereac17b82016-02-19 03:27:46 +0000344 Called by the server's constructor to bind the socket to the desired address.
345 May be overridden.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Martin Pantereac17b82016-02-19 03:27:46 +0000348 .. method:: verify_request(request, client_address)
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Martin Pantereac17b82016-02-19 03:27:46 +0000350 Must return a Boolean value; if the value is :const:`True`, the request will
351 be processed, and if it's :const:`False`, the request will be denied. This
352 function can be overridden to implement access controls for a server. The
353 default implementation always returns :const:`True`.
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Martin Pantereac17b82016-02-19 03:27:46 +0000356Request Handler Objects
357-----------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Martin Pantereac17b82016-02-19 03:27:46 +0000359.. class:: BaseRequestHandler
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Martin Pantereac17b82016-02-19 03:27:46 +0000361 This is the superclass of all request handler objects. It defines
362 the interface, given below. A concrete request handler subclass must
363 define a new :meth:`handle` method, and can override any of
364 the other methods. A new instance of the subclass is created for each
365 request.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367
Martin Pantereac17b82016-02-19 03:27:46 +0000368 .. method:: setup()
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Martin Pantereac17b82016-02-19 03:27:46 +0000370 Called before the :meth:`handle` method to perform any initialization actions
371 required. The default implementation does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373
Martin Pantereac17b82016-02-19 03:27:46 +0000374 .. method:: handle()
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Martin Pantereac17b82016-02-19 03:27:46 +0000376 This function must do all the work required to service a request. The
377 default implementation does nothing. Several instance attributes are
378 available to it; the request is available as :attr:`self.request`; the client
379 address as :attr:`self.client_address`; and the server instance as
380 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Martin Pantereac17b82016-02-19 03:27:46 +0000382 The type of :attr:`self.request` is different for datagram or stream
383 services. For stream services, :attr:`self.request` is a socket object; for
384 datagram services, :attr:`self.request` is a pair of string and socket.
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Martin Pantereac17b82016-02-19 03:27:46 +0000387 .. method:: finish()
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Martin Pantereac17b82016-02-19 03:27:46 +0000389 Called after the :meth:`handle` method to perform any clean-up actions
390 required. The default implementation does nothing. If :meth:`setup`
391 raises an exception, this function will not be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
393
Martin Pantereac17b82016-02-19 03:27:46 +0000394.. class:: StreamRequestHandler
395 DatagramRequestHandler
Georg Brandl116aa622007-08-15 14:28:22 +0000396
Martin Pantereac17b82016-02-19 03:27:46 +0000397 These :class:`BaseRequestHandler` subclasses override the
398 :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish`
399 methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes.
400 The :attr:`self.rfile` and :attr:`self.wfile` attributes can be
401 read or written, respectively, to get the request data or return data
402 to the client.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
Georg Brandlb533e262008-05-25 18:19:30 +0000404
405Examples
406--------
407
408:class:`socketserver.TCPServer` Example
409~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
410
411This is the server side::
412
413 import socketserver
414
415 class MyTCPHandler(socketserver.BaseRequestHandler):
416 """
Martin Pantereac17b82016-02-19 03:27:46 +0000417 The request handler class for our server.
Georg Brandlb533e262008-05-25 18:19:30 +0000418
419 It is instantiated once per connection to the server, and must
420 override the handle() method to implement communication to the
421 client.
422 """
423
424 def handle(self):
425 # self.request is the TCP socket connected to the client
426 self.data = self.request.recv(1024).strip()
Florent Xicluna023611f2011-10-23 22:40:37 +0200427 print("{} wrote:".format(self.client_address[0]))
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000428 print(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000429 # just send back the same data, but upper-cased
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800430 self.request.sendall(self.data.upper())
Georg Brandlb533e262008-05-25 18:19:30 +0000431
432 if __name__ == "__main__":
433 HOST, PORT = "localhost", 9999
434
435 # Create the server, binding to localhost on port 9999
436 server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
437
438 # Activate the server; this will keep running until you
439 # interrupt the program with Ctrl-C
440 server.serve_forever()
441
442An alternative request handler class that makes use of streams (file-like
443objects that simplify communication by providing the standard file interface)::
444
445 class MyTCPHandler(socketserver.StreamRequestHandler):
446
447 def handle(self):
448 # self.rfile is a file-like object created by the handler;
449 # we can now use e.g. readline() instead of raw recv() calls
450 self.data = self.rfile.readline().strip()
Florent Xicluna023611f2011-10-23 22:40:37 +0200451 print("{} wrote:".format(self.client_address[0]))
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000452 print(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000453 # Likewise, self.wfile is a file-like object used to write back
454 # to the client
455 self.wfile.write(self.data.upper())
456
457The difference is that the ``readline()`` call in the second handler will call
458``recv()`` multiple times until it encounters a newline character, while the
459single ``recv()`` call in the first handler will just return what has been sent
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800460from the client in one ``sendall()`` call.
Georg Brandlb533e262008-05-25 18:19:30 +0000461
462
463This is the client side::
464
465 import socket
466 import sys
467
468 HOST, PORT = "localhost", 9999
469 data = " ".join(sys.argv[1:])
470
471 # Create a socket (SOCK_STREAM means a TCP socket)
472 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
473
Florent Xicluna023611f2011-10-23 22:40:37 +0200474 try:
475 # Connect to server and send data
476 sock.connect((HOST, PORT))
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800477 sock.sendall(bytes(data + "\n", "utf-8"))
Georg Brandlb533e262008-05-25 18:19:30 +0000478
Florent Xicluna023611f2011-10-23 22:40:37 +0200479 # Receive data from the server and shut down
480 received = str(sock.recv(1024), "utf-8")
481 finally:
482 sock.close()
Georg Brandlb533e262008-05-25 18:19:30 +0000483
Florent Xicluna023611f2011-10-23 22:40:37 +0200484 print("Sent: {}".format(data))
485 print("Received: {}".format(received))
Georg Brandlb533e262008-05-25 18:19:30 +0000486
487
488The output of the example should look something like this:
489
490Server::
491
492 $ python TCPServer.py
493 127.0.0.1 wrote:
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000494 b'hello world with TCP'
Georg Brandlb533e262008-05-25 18:19:30 +0000495 127.0.0.1 wrote:
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000496 b'python is nice'
Georg Brandlb533e262008-05-25 18:19:30 +0000497
498Client::
499
500 $ python TCPClient.py hello world with TCP
501 Sent: hello world with TCP
Florent Xicluna023611f2011-10-23 22:40:37 +0200502 Received: HELLO WORLD WITH TCP
Georg Brandlb533e262008-05-25 18:19:30 +0000503 $ python TCPClient.py python is nice
504 Sent: python is nice
Florent Xicluna023611f2011-10-23 22:40:37 +0200505 Received: PYTHON IS NICE
Georg Brandlb533e262008-05-25 18:19:30 +0000506
507
508:class:`socketserver.UDPServer` Example
509~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
510
511This is the server side::
512
513 import socketserver
514
515 class MyUDPHandler(socketserver.BaseRequestHandler):
516 """
517 This class works similar to the TCP handler class, except that
518 self.request consists of a pair of data and client socket, and since
519 there is no connection the client address must be given explicitly
520 when sending data back via sendto().
521 """
522
523 def handle(self):
524 data = self.request[0].strip()
525 socket = self.request[1]
Florent Xicluna023611f2011-10-23 22:40:37 +0200526 print("{} wrote:".format(self.client_address[0]))
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000527 print(data)
Georg Brandlb533e262008-05-25 18:19:30 +0000528 socket.sendto(data.upper(), self.client_address)
529
530 if __name__ == "__main__":
Benjamin Peterson20211002009-11-25 18:34:42 +0000531 HOST, PORT = "localhost", 9999
532 server = socketserver.UDPServer((HOST, PORT), MyUDPHandler)
533 server.serve_forever()
Georg Brandlb533e262008-05-25 18:19:30 +0000534
535This is the client side::
536
537 import socket
538 import sys
539
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000540 HOST, PORT = "localhost", 9999
Georg Brandlb533e262008-05-25 18:19:30 +0000541 data = " ".join(sys.argv[1:])
542
543 # SOCK_DGRAM is the socket type to use for UDP sockets
544 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
545
546 # As you can see, there is no connect() call; UDP has no connections.
547 # Instead, data is directly sent to the recipient via sendto().
Florent Xicluna023611f2011-10-23 22:40:37 +0200548 sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT))
549 received = str(sock.recv(1024), "utf-8")
Georg Brandlb533e262008-05-25 18:19:30 +0000550
Florent Xicluna023611f2011-10-23 22:40:37 +0200551 print("Sent: {}".format(data))
552 print("Received: {}".format(received))
Georg Brandlb533e262008-05-25 18:19:30 +0000553
554The output of the example should look exactly like for the TCP server example.
555
556
557Asynchronous Mixins
558~~~~~~~~~~~~~~~~~~~
559
560To build asynchronous handlers, use the :class:`ThreadingMixIn` and
561:class:`ForkingMixIn` classes.
562
563An example for the :class:`ThreadingMixIn` class::
564
565 import socket
566 import threading
567 import socketserver
568
569 class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
570
571 def handle(self):
Florent Xicluna023611f2011-10-23 22:40:37 +0200572 data = str(self.request.recv(1024), 'ascii')
Georg Brandlf9926402008-06-13 06:32:25 +0000573 cur_thread = threading.current_thread()
Florent Xicluna023611f2011-10-23 22:40:37 +0200574 response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800575 self.request.sendall(response)
Georg Brandlb533e262008-05-25 18:19:30 +0000576
577 class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
578 pass
579
580 def client(ip, port, message):
581 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
582 sock.connect((ip, port))
Florent Xicluna023611f2011-10-23 22:40:37 +0200583 try:
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800584 sock.sendall(bytes(message, 'ascii'))
Florent Xicluna023611f2011-10-23 22:40:37 +0200585 response = str(sock.recv(1024), 'ascii')
586 print("Received: {}".format(response))
587 finally:
588 sock.close()
Georg Brandlb533e262008-05-25 18:19:30 +0000589
590 if __name__ == "__main__":
591 # Port 0 means to select an arbitrary unused port
592 HOST, PORT = "localhost", 0
593
594 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
595 ip, port = server.server_address
596
597 # Start a thread with the server -- that thread will then start one
598 # more thread for each request
599 server_thread = threading.Thread(target=server.serve_forever)
600 # Exit the server thread when the main thread terminates
Florent Xicluna023611f2011-10-23 22:40:37 +0200601 server_thread.daemon = True
Georg Brandlb533e262008-05-25 18:19:30 +0000602 server_thread.start()
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000603 print("Server loop running in thread:", server_thread.name)
Georg Brandlb533e262008-05-25 18:19:30 +0000604
Florent Xicluna023611f2011-10-23 22:40:37 +0200605 client(ip, port, "Hello World 1")
606 client(ip, port, "Hello World 2")
607 client(ip, port, "Hello World 3")
Georg Brandlb533e262008-05-25 18:19:30 +0000608
609 server.shutdown()
Robert Collins1ee92832015-07-29 12:52:40 +1200610 server.server_close()
Georg Brandlb533e262008-05-25 18:19:30 +0000611
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000612
Georg Brandlb533e262008-05-25 18:19:30 +0000613The output of the example should look something like this::
614
615 $ python ThreadedTCPServer.py
616 Server loop running in thread: Thread-1
Florent Xicluna023611f2011-10-23 22:40:37 +0200617 Received: Thread-2: Hello World 1
618 Received: Thread-3: Hello World 2
619 Received: Thread-4: Hello World 3
Georg Brandlb533e262008-05-25 18:19:30 +0000620
621
622The :class:`ForkingMixIn` class is used in the same way, except that the server
623will spawn a new process for each request.