blob: a81214e906c5dcbd6f4ee3c91415dd09992c8c7f [file] [log] [blame]
Georg Brandle152a772008-05-24 18:31:28 +00001:mod:`SocketServer` --- A framework for network servers
Georg Brandl8ec7f652007-08-15 14:28:01 +00002=======================================================
3
Georg Brandl7a148c22008-05-12 10:03:16 +00004.. module:: SocketServer
Georg Brandl8ec7f652007-08-15 14:28:01 +00005 :synopsis: A framework for network servers.
Georg Brandl7a148c22008-05-12 10:03:16 +00006
7.. note::
Georg Brandle152a772008-05-24 18:31:28 +00008
Georg Brandle92818f2009-01-03 20:47:01 +00009 The :mod:`SocketServer` module has been renamed to :mod:`socketserver` in
Ezio Melotti510ff542012-05-03 19:21:40 +030010 Python 3. The :term:`2to3` tool will automatically adapt imports when
11 converting your sources to Python 3.
Alexandre Vassalottifea23a42008-05-12 02:18:15 +000012
Éric Araujo29a0b572011-08-19 02:14:03 +020013**Source code:** :source:`Lib/SocketServer.py`
14
15--------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000016
Georg Brandle152a772008-05-24 18:31:28 +000017The :mod:`SocketServer` module simplifies the task of writing network servers.
Georg Brandl8ec7f652007-08-15 14:28:01 +000018
Martin Panter94035f32016-02-19 03:27:46 +000019There are four basic concrete server classes:
20
21
22.. class:: TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
23
24 This uses the Internet TCP protocol, which provides for
25 continuous streams of data between the client and server.
26 If *bind_and_activate* is true, the constructor automatically attempts to
27 invoke :meth:`~BaseServer.server_bind` and
28 :meth:`~BaseServer.server_activate`. The other parameters are passed to
29 the :class:`BaseServer` base class.
30
31
32.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
33
34 This uses datagrams, which are discrete packets of information that may
35 arrive out of order or be lost while in transit. The parameters are
36 the same as for :class:`TCPServer`.
37
38
39.. class:: UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
40 UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)
41
42 These more infrequently used classes are similar to the TCP and
43 UDP classes, but use Unix domain sockets; they're not available on
44 non-Unix platforms. The parameters are the same as for
45 :class:`TCPServer`.
46
Georg Brandl8ec7f652007-08-15 14:28:01 +000047
48These four classes process requests :dfn:`synchronously`; each request must be
49completed before the next request can be started. This isn't suitable if each
50request takes a long time to complete, because it requires a lot of computation,
51or because it returns a lot of data which the client is slow to process. The
52solution is to create a separate process or thread to handle each request; the
53:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes can be used to
54support asynchronous behaviour.
55
56Creating a server requires several steps. First, you must create a request
57handler class by subclassing the :class:`BaseRequestHandler` class and
Martin Panter94035f32016-02-19 03:27:46 +000058overriding its :meth:`~BaseRequestHandler.handle` method;
59this method will process incoming
Georg Brandl8ec7f652007-08-15 14:28:01 +000060requests. Second, you must instantiate one of the server classes, passing it
Robert Collins2f2c8292015-07-29 12:48:42 +120061the server's address and the request handler class. Then call the
Martin Panter94035f32016-02-19 03:27:46 +000062:meth:`~BaseServer.handle_request` or
63:meth:`~BaseServer.serve_forever` method of the server object to
Robert Collins2f2c8292015-07-29 12:48:42 +120064process one or many requests. Finally, call :meth:`~BaseServer.server_close`
65to close the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
67When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
68you should explicitly declare how you want your threads to behave on an abrupt
69shutdown. The :class:`ThreadingMixIn` class defines an attribute
70*daemon_threads*, which indicates whether or not the server should wait for
71thread termination. You should set the flag explicitly if you would like threads
72to behave autonomously; the default is :const:`False`, meaning that Python will
73not exit until all threads created by :class:`ThreadingMixIn` have exited.
74
75Server classes have the same external methods and attributes, no matter what
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +000076network protocol they use.
Georg Brandl8ec7f652007-08-15 14:28:01 +000077
78
79Server Creation Notes
80---------------------
81
82There are five classes in an inheritance diagram, four of which represent
83synchronous servers of four types::
84
85 +------------+
86 | BaseServer |
87 +------------+
88 |
89 v
90 +-----------+ +------------------+
91 | TCPServer |------->| UnixStreamServer |
92 +-----------+ +------------------+
93 |
94 v
95 +-----------+ +--------------------+
96 | UDPServer |------->| UnixDatagramServer |
97 +-----------+ +--------------------+
98
99Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
100:class:`UnixStreamServer` --- the only difference between an IP and a Unix
101stream server is the address family, which is simply repeated in both Unix
102server classes.
103
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104
Martin Panter94035f32016-02-19 03:27:46 +0000105.. class:: ForkingMixIn
106 ThreadingMixIn
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
Martin Panter94035f32016-02-19 03:27:46 +0000108 Forking and threading versions of each type of server can be created
109 using these mix-in classes. For instance, :class:`ThreadingUDPServer`
110 is created as follows::
111
112 class ThreadingUDPServer(ThreadingMixIn, UDPServer):
113 pass
114
115 The mix-in class comes first, since it overrides a method defined in
116 :class:`UDPServer`. Setting the various attributes also changes the
117 behavior of the underlying server mechanism.
118
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)c3cd60e2016-06-03 05:48:23 +0000119 :class:`ForkingMixIn` and the Forking classes mentioned below are
120 only available on POSIX platforms that support :func:`~os.fork`.
121
Martin Panter94035f32016-02-19 03:27:46 +0000122
123.. class:: ForkingTCPServer
124 ForkingUDPServer
125 ThreadingTCPServer
126 ThreadingUDPServer
127
128 These classes are pre-defined using the mix-in classes.
129
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130
131To implement a service, you must derive a class from :class:`BaseRequestHandler`
Martin Panter94035f32016-02-19 03:27:46 +0000132and redefine its :meth:`~BaseRequestHandler.handle` method.
133You can then run various versions of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000134the service by combining one of the server classes with your request handler
135class. The request handler class must be different for datagram or stream
136services. This can be hidden by using the handler subclasses
137:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
138
139Of course, you still have to use your head! For instance, it makes no sense to
140use a forking server if the service contains state in memory that can be
141modified by different requests, since the modifications in the child process
142would never reach the initial state kept in the parent process and passed to
143each child. In this case, you can use a threading server, but you will probably
144have to use locks to protect the integrity of the shared data.
145
146On the other hand, if you are building an HTTP server where all data is stored
147externally (for instance, in the file system), a synchronous class will
148essentially render the service "deaf" while one request is being handled --
149which may be for a very long time if a client is slow to receive all the data it
150has requested. Here a threading or forking server is appropriate.
151
152In some cases, it may be appropriate to process part of a request synchronously,
153but to finish processing in a forked child depending on the request data. This
154can be implemented by using a synchronous server and doing an explicit fork in
Martin Panter94035f32016-02-19 03:27:46 +0000155the request handler class :meth:`~BaseRequestHandler.handle` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000156
157Another approach to handling multiple simultaneous requests in an environment
Serhiy Storchakab33336f2013-10-13 23:09:00 +0300158that supports neither threads nor :func:`~os.fork` (or where these are too
159expensive or inappropriate for the service) is to maintain an explicit table of
160partially finished requests and to use :func:`~select.select` to decide which
161request to work on next (or whether to handle a new incoming request). This is
162particularly important for stream services where each client can potentially be
163connected for a long time (if threads or subprocesses cannot be used). See
164:mod:`asyncore` for another way to manage this.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000165
Georg Brandlb19be572007-12-29 10:57:00 +0000166.. XXX should data and methods be intermingled, or separate?
167 how should the distinction between class and instance variables be drawn?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000168
169
170Server Objects
171--------------
172
Martin Panter94035f32016-02-19 03:27:46 +0000173.. class:: BaseServer(server_address, RequestHandlerClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
Georg Brandl9af0c562009-04-05 10:24:20 +0000175 This is the superclass of all Server objects in the module. It defines the
176 interface, given below, but does not implement most of the methods, which is
Martin Panter94035f32016-02-19 03:27:46 +0000177 done in subclasses. The two parameters are stored in the respective
178 :attr:`server_address` and :attr:`RequestHandlerClass` attributes.
Georg Brandl9af0c562009-04-05 10:24:20 +0000179
180
Martin Panter94035f32016-02-19 03:27:46 +0000181 .. method:: fileno()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
Martin Panter94035f32016-02-19 03:27:46 +0000183 Return an integer file descriptor for the socket on which the server is
184 listening. This function is most commonly passed to :func:`select.select`, to
185 allow monitoring multiple servers in the same process.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000186
187
Martin Panter94035f32016-02-19 03:27:46 +0000188 .. method:: handle_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189
Martin Panter94035f32016-02-19 03:27:46 +0000190 Process a single request. This function calls the following methods in
191 order: :meth:`get_request`, :meth:`verify_request`, and
192 :meth:`process_request`. If the user-provided
193 :meth:`~BaseRequestHandler.handle` method of the
194 handler class raises an exception, the server's :meth:`handle_error` method
195 will be called. If no request is received within :attr:`timeout`
196 seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
197 will return.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198
199
Martin Panter94035f32016-02-19 03:27:46 +0000200 .. method:: serve_forever(poll_interval=0.5)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000201
Martin Panter94035f32016-02-19 03:27:46 +0000202 Handle requests until an explicit :meth:`shutdown` request. Poll for
203 shutdown every *poll_interval* seconds.
204 Ignores the :attr:`timeout` attribute.
205 If you need to do periodic tasks, do them in another thread.
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000206
207
Martin Panter94035f32016-02-19 03:27:46 +0000208 .. method:: shutdown()
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000209
Martin Panter94035f32016-02-19 03:27:46 +0000210 Tell the :meth:`serve_forever` loop to stop and wait until it does.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
Martin Panter94035f32016-02-19 03:27:46 +0000212 .. versionadded:: 2.6
Georg Brandl910df2f2008-06-26 18:55:37 +0000213
Georg Brandl8ec7f652007-08-15 14:28:01 +0000214
Martin Panter94035f32016-02-19 03:27:46 +0000215 .. method:: server_close()
Robert Collins2f2c8292015-07-29 12:48:42 +1200216
Martin Panter94035f32016-02-19 03:27:46 +0000217 Clean up the server. May be overridden.
Robert Collins2f2c8292015-07-29 12:48:42 +1200218
Martin Panter94035f32016-02-19 03:27:46 +0000219 .. versionadded:: 2.6
Robert Collins2f2c8292015-07-29 12:48:42 +1200220
221
Martin Panter94035f32016-02-19 03:27:46 +0000222 .. attribute:: address_family
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223
Martin Panter94035f32016-02-19 03:27:46 +0000224 The family of protocols to which the server's socket belongs.
225 Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226
227
Martin Panter94035f32016-02-19 03:27:46 +0000228 .. attribute:: RequestHandlerClass
Georg Brandl8ec7f652007-08-15 14:28:01 +0000229
Martin Panter94035f32016-02-19 03:27:46 +0000230 The user-provided request handler class; an instance of this class is created
231 for each request.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000232
233
Martin Panter94035f32016-02-19 03:27:46 +0000234 .. attribute:: server_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000235
Martin Panter94035f32016-02-19 03:27:46 +0000236 The address on which the server is listening. The format of addresses varies
237 depending on the protocol family;
238 see the documentation for the :mod:`socket` module
239 for details. For Internet protocols, this is a tuple containing a string giving
240 the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241
242
Martin Panter94035f32016-02-19 03:27:46 +0000243 .. attribute:: socket
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
Martin Panter94035f32016-02-19 03:27:46 +0000245 The socket object on which the server will listen for incoming requests.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246
Georg Brandl9af0c562009-04-05 10:24:20 +0000247
Martin Panter94035f32016-02-19 03:27:46 +0000248 The server classes support the following class variables:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000249
Martin Panter94035f32016-02-19 03:27:46 +0000250 .. XXX should class variables be covered before instance variables, or vice versa?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251
Martin Panter94035f32016-02-19 03:27:46 +0000252 .. attribute:: allow_reuse_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253
Martin Panter94035f32016-02-19 03:27:46 +0000254 Whether the server will allow the reuse of an address. This defaults to
255 :const:`False`, and can be set in subclasses to change the policy.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256
257
Martin Panter94035f32016-02-19 03:27:46 +0000258 .. attribute:: request_queue_size
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
Martin Panter94035f32016-02-19 03:27:46 +0000260 The size of the request queue. If it takes a long time to process a single
261 request, any requests that arrive while the server is busy are placed into a
262 queue, up to :attr:`request_queue_size` requests. Once the queue is full,
263 further requests from clients will get a "Connection denied" error. The default
264 value is usually 5, but this can be overridden by subclasses.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000265
266
Martin Panter94035f32016-02-19 03:27:46 +0000267 .. attribute:: socket_type
Georg Brandl8ec7f652007-08-15 14:28:01 +0000268
Martin Panter94035f32016-02-19 03:27:46 +0000269 The type of socket used by the server; :const:`socket.SOCK_STREAM` and
270 :const:`socket.SOCK_DGRAM` are two common values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000271
Georg Brandl9af0c562009-04-05 10:24:20 +0000272
Martin Panter94035f32016-02-19 03:27:46 +0000273 .. attribute:: timeout
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000274
Martin Panter94035f32016-02-19 03:27:46 +0000275 Timeout duration, measured in seconds, or :const:`None` if no timeout is
276 desired. If :meth:`handle_request` receives no incoming requests within the
277 timeout period, the :meth:`handle_timeout` method is called.
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000278
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200279
Martin Panter94035f32016-02-19 03:27:46 +0000280 There are various server methods that can be overridden by subclasses of base
281 server classes like :class:`TCPServer`; these methods aren't useful to external
282 users of the server object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
Martin Panter94035f32016-02-19 03:27:46 +0000284 .. XXX should the default implementations of these be documented, or should
285 it be assumed that the user will look at SocketServer.py?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286
Martin Panter94035f32016-02-19 03:27:46 +0000287 .. method:: finish_request()
288
289 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
290 calling its :meth:`~BaseRequestHandler.handle` method.
291
292
293 .. method:: get_request()
294
295 Must accept a request from the socket, and return a 2-tuple containing the *new*
296 socket object to be used to communicate with the client, and the client's
297 address.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000298
Georg Brandl8ec7f652007-08-15 14:28:01 +0000299
Martin Panter94035f32016-02-19 03:27:46 +0000300 .. method:: handle_error(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000301
Martin Panter94035f32016-02-19 03:27:46 +0000302 This function is called if the :meth:`~BaseRequestHandler.handle`
303 method of a :attr:`RequestHandlerClass` instance raises
304 an exception. The default action is to print the traceback to
305 standard output and continue handling further requests.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307
Martin Panter94035f32016-02-19 03:27:46 +0000308 .. method:: handle_timeout()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000309
Martin Panter94035f32016-02-19 03:27:46 +0000310 This function is called when the :attr:`timeout` attribute has been set to a
311 value other than :const:`None` and the timeout period has passed with no
312 requests being received. The default action for forking servers is
313 to collect the status of any child processes that have exited, while
314 in threading servers this method does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000315
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316
Martin Panter94035f32016-02-19 03:27:46 +0000317 .. method:: process_request(request, client_address)
Georg Brandl9af0c562009-04-05 10:24:20 +0000318
Martin Panter94035f32016-02-19 03:27:46 +0000319 Calls :meth:`finish_request` to create an instance of the
320 :attr:`RequestHandlerClass`. If desired, this function can create a new process
321 or thread to handle the request; the :class:`ForkingMixIn` and
322 :class:`ThreadingMixIn` classes do this.
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000323
Georg Brandl8ec7f652007-08-15 14:28:01 +0000324
Martin Panter94035f32016-02-19 03:27:46 +0000325 .. Is there any point in documenting the following two functions?
326 What would the purpose of overriding them be: initializing server
327 instance variables, adding new network families?
Georg Brandl9af0c562009-04-05 10:24:20 +0000328
Martin Panter94035f32016-02-19 03:27:46 +0000329 .. method:: server_activate()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000330
Martin Panter94035f32016-02-19 03:27:46 +0000331 Called by the server's constructor to activate the server. The default behavior
332 for a TCP server just invokes :meth:`~socket.socket.listen`
333 on the server's socket. May be overridden.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334
Georg Brandl9af0c562009-04-05 10:24:20 +0000335
Martin Panter94035f32016-02-19 03:27:46 +0000336 .. method:: server_bind()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000337
Martin Panter94035f32016-02-19 03:27:46 +0000338 Called by the server's constructor to bind the socket to the desired address.
339 May be overridden.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000340
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341
Martin Panter94035f32016-02-19 03:27:46 +0000342 .. method:: verify_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
Martin Panter94035f32016-02-19 03:27:46 +0000344 Must return a Boolean value; if the value is :const:`True`, the request will be
345 processed, and if it's :const:`False`, the request will be denied. This function
346 can be overridden to implement access controls for a server. The default
347 implementation always returns :const:`True`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000348
Georg Brandl8ec7f652007-08-15 14:28:01 +0000349
Martin Panter94035f32016-02-19 03:27:46 +0000350Request Handler Objects
351-----------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000352
Martin Panter94035f32016-02-19 03:27:46 +0000353.. class:: BaseRequestHandler
Georg Brandl8ec7f652007-08-15 14:28:01 +0000354
Martin Panter94035f32016-02-19 03:27:46 +0000355 This is the superclass of all request handler objects. It defines
356 the interface, given below. A concrete request handler subclass must
357 define a new :meth:`handle` method, and can override any of
358 the other methods. A new instance of the subclass is created for each
359 request.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360
361
Martin Panter94035f32016-02-19 03:27:46 +0000362 .. method:: setup()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363
Martin Panter94035f32016-02-19 03:27:46 +0000364 Called before the :meth:`handle` method to perform any initialization actions
365 required. The default implementation does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000366
367
Martin Panter94035f32016-02-19 03:27:46 +0000368 .. method:: handle()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000369
Martin Panter94035f32016-02-19 03:27:46 +0000370 This function must do all the work required to service a request. The
371 default implementation does nothing. Several instance attributes are
372 available to it; the request is available as :attr:`self.request`; the client
373 address as :attr:`self.client_address`; and the server instance as
374 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000375
Martin Panter94035f32016-02-19 03:27:46 +0000376 The type of :attr:`self.request` is different for datagram or stream
377 services. For stream services, :attr:`self.request` is a socket object; for
378 datagram services, :attr:`self.request` is a pair of string and socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000379
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
Martin Panter94035f32016-02-19 03:27:46 +0000381 .. method:: finish()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000382
Martin Panter94035f32016-02-19 03:27:46 +0000383 Called after the :meth:`handle` method to perform any clean-up actions
384 required. The default implementation does nothing. If :meth:`setup`
385 raises an exception, this function will not be called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000386
387
Martin Panter94035f32016-02-19 03:27:46 +0000388.. class:: StreamRequestHandler
389 DatagramRequestHandler
Georg Brandl8ec7f652007-08-15 14:28:01 +0000390
Martin Panter94035f32016-02-19 03:27:46 +0000391 These :class:`BaseRequestHandler` subclasses override the
392 :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish`
393 methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes.
394 The :attr:`self.rfile` and :attr:`self.wfile` attributes can be
395 read or written, respectively, to get the request data or return data
396 to the client.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000397
Georg Brandl67d69332008-05-18 08:52:59 +0000398
399Examples
400--------
401
Georg Brandle152a772008-05-24 18:31:28 +0000402:class:`SocketServer.TCPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000403~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
404
405This is the server side::
406
Georg Brandle152a772008-05-24 18:31:28 +0000407 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000408
Georg Brandle152a772008-05-24 18:31:28 +0000409 class MyTCPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000410 """
Martin Panter94035f32016-02-19 03:27:46 +0000411 The request handler class for our server.
Georg Brandl67d69332008-05-18 08:52:59 +0000412
413 It is instantiated once per connection to the server, and must
414 override the handle() method to implement communication to the
415 client.
416 """
417
418 def handle(self):
419 # self.request is the TCP socket connected to the client
420 self.data = self.request.recv(1024).strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200421 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000422 print self.data
423 # just send back the same data, but upper-cased
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800424 self.request.sendall(self.data.upper())
Georg Brandl67d69332008-05-18 08:52:59 +0000425
426 if __name__ == "__main__":
427 HOST, PORT = "localhost", 9999
428
429 # Create the server, binding to localhost on port 9999
Georg Brandle152a772008-05-24 18:31:28 +0000430 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
Georg Brandl67d69332008-05-18 08:52:59 +0000431
432 # Activate the server; this will keep running until you
433 # interrupt the program with Ctrl-C
434 server.serve_forever()
435
436An alternative request handler class that makes use of streams (file-like
437objects that simplify communication by providing the standard file interface)::
438
Georg Brandle152a772008-05-24 18:31:28 +0000439 class MyTCPHandler(SocketServer.StreamRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000440
441 def handle(self):
442 # self.rfile is a file-like object created by the handler;
443 # we can now use e.g. readline() instead of raw recv() calls
444 self.data = self.rfile.readline().strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200445 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000446 print self.data
447 # Likewise, self.wfile is a file-like object used to write back
448 # to the client
449 self.wfile.write(self.data.upper())
450
451The difference is that the ``readline()`` call in the second handler will call
452``recv()`` multiple times until it encounters a newline character, while the
453single ``recv()`` call in the first handler will just return what has been sent
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800454from the client in one ``sendall()`` call.
Georg Brandl67d69332008-05-18 08:52:59 +0000455
456
457This is the client side::
458
459 import socket
460 import sys
461
462 HOST, PORT = "localhost", 9999
463 data = " ".join(sys.argv[1:])
464
465 # Create a socket (SOCK_STREAM means a TCP socket)
466 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
467
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200468 try:
469 # Connect to server and send data
470 sock.connect((HOST, PORT))
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800471 sock.sendall(data + "\n")
Georg Brandl67d69332008-05-18 08:52:59 +0000472
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200473 # Receive data from the server and shut down
474 received = sock.recv(1024)
475 finally:
476 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000477
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200478 print "Sent: {}".format(data)
479 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000480
481
482The output of the example should look something like this:
483
Martin Panter8f1dd222016-07-26 11:18:21 +0200484Server:
485
486.. code-block:: shell-session
Georg Brandl67d69332008-05-18 08:52:59 +0000487
488 $ python TCPServer.py
489 127.0.0.1 wrote:
490 hello world with TCP
491 127.0.0.1 wrote:
492 python is nice
493
Martin Panter8f1dd222016-07-26 11:18:21 +0200494Client:
495
496.. code-block:: shell-session
Georg Brandl67d69332008-05-18 08:52:59 +0000497
498 $ python TCPClient.py hello world with TCP
499 Sent: hello world with TCP
500 Received: HELLO WORLD WITH TCP
501 $ python TCPClient.py python is nice
502 Sent: python is nice
503 Received: PYTHON IS NICE
504
505
Georg Brandle152a772008-05-24 18:31:28 +0000506:class:`SocketServer.UDPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000507~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
508
509This is the server side::
510
Georg Brandle152a772008-05-24 18:31:28 +0000511 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000512
Georg Brandle152a772008-05-24 18:31:28 +0000513 class MyUDPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000514 """
515 This class works similar to the TCP handler class, except that
516 self.request consists of a pair of data and client socket, and since
517 there is no connection the client address must be given explicitly
518 when sending data back via sendto().
519 """
520
521 def handle(self):
522 data = self.request[0].strip()
523 socket = self.request[1]
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200524 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000525 print data
526 socket.sendto(data.upper(), self.client_address)
527
528 if __name__ == "__main__":
R. David Murray48239612009-11-20 13:29:43 +0000529 HOST, PORT = "localhost", 9999
530 server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
531 server.serve_forever()
Georg Brandl67d69332008-05-18 08:52:59 +0000532
533This is the client side::
534
535 import socket
536 import sys
537
Georg Brandle8ddbec2009-08-24 17:22:05 +0000538 HOST, PORT = "localhost", 9999
Georg Brandl67d69332008-05-18 08:52:59 +0000539 data = " ".join(sys.argv[1:])
540
541 # SOCK_DGRAM is the socket type to use for UDP sockets
542 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
543
544 # As you can see, there is no connect() call; UDP has no connections.
545 # Instead, data is directly sent to the recipient via sendto().
546 sock.sendto(data + "\n", (HOST, PORT))
547 received = sock.recv(1024)
548
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200549 print "Sent: {}".format(data)
550 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000551
552The output of the example should look exactly like for the TCP server example.
553
554
555Asynchronous Mixins
556~~~~~~~~~~~~~~~~~~~
557
558To build asynchronous handlers, use the :class:`ThreadingMixIn` and
559:class:`ForkingMixIn` classes.
560
561An example for the :class:`ThreadingMixIn` class::
562
563 import socket
564 import threading
Georg Brandle152a772008-05-24 18:31:28 +0000565 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000566
Georg Brandle152a772008-05-24 18:31:28 +0000567 class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000568
569 def handle(self):
570 data = self.request.recv(1024)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200571 cur_thread = threading.current_thread()
572 response = "{}: {}".format(cur_thread.name, data)
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800573 self.request.sendall(response)
Georg Brandl67d69332008-05-18 08:52:59 +0000574
Georg Brandle152a772008-05-24 18:31:28 +0000575 class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
Georg Brandl67d69332008-05-18 08:52:59 +0000576 pass
577
578 def client(ip, port, message):
579 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
580 sock.connect((ip, port))
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200581 try:
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800582 sock.sendall(message)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200583 response = sock.recv(1024)
584 print "Received: {}".format(response)
585 finally:
586 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000587
588 if __name__ == "__main__":
589 # Port 0 means to select an arbitrary unused port
590 HOST, PORT = "localhost", 0
591
592 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
593 ip, port = server.server_address
594
595 # Start a thread with the server -- that thread will then start one
596 # more thread for each request
597 server_thread = threading.Thread(target=server.serve_forever)
598 # Exit the server thread when the main thread terminates
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200599 server_thread.daemon = True
Georg Brandl67d69332008-05-18 08:52:59 +0000600 server_thread.start()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200601 print "Server loop running in thread:", server_thread.name
Georg Brandl67d69332008-05-18 08:52:59 +0000602
603 client(ip, port, "Hello World 1")
604 client(ip, port, "Hello World 2")
605 client(ip, port, "Hello World 3")
606
607 server.shutdown()
Robert Collins2f2c8292015-07-29 12:48:42 +1200608 server.server_close()
Georg Brandl67d69332008-05-18 08:52:59 +0000609
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200610
Martin Panter8f1dd222016-07-26 11:18:21 +0200611The output of the example should look something like this:
612
613.. code-block:: shell-session
Georg Brandl67d69332008-05-18 08:52:59 +0000614
615 $ python ThreadedTCPServer.py
616 Server loop running in thread: Thread-1
617 Received: Thread-2: Hello World 1
618 Received: Thread-3: Hello World 2
619 Received: Thread-4: Hello World 3
620
621
622The :class:`ForkingMixIn` class is used in the same way, except that the server
623will spawn a new process for each request.
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)c3cd60e2016-06-03 05:48:23 +0000624Available only on POSIX platforms that support :func:`~os.fork`.