blob: af2e25385c63aced757db21c05161bb5f6f373b9 [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
119
120.. class:: ForkingTCPServer
121 ForkingUDPServer
122 ThreadingTCPServer
123 ThreadingUDPServer
124
125 These classes are pre-defined using the mix-in classes.
126
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
128To implement a service, you must derive a class from :class:`BaseRequestHandler`
Martin Panter94035f32016-02-19 03:27:46 +0000129and redefine its :meth:`~BaseRequestHandler.handle` method.
130You can then run various versions of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000131the service by combining one of the server classes with your request handler
132class. The request handler class must be different for datagram or stream
133services. This can be hidden by using the handler subclasses
134:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
135
136Of course, you still have to use your head! For instance, it makes no sense to
137use a forking server if the service contains state in memory that can be
138modified by different requests, since the modifications in the child process
139would never reach the initial state kept in the parent process and passed to
140each child. In this case, you can use a threading server, but you will probably
141have to use locks to protect the integrity of the shared data.
142
143On the other hand, if you are building an HTTP server where all data is stored
144externally (for instance, in the file system), a synchronous class will
145essentially render the service "deaf" while one request is being handled --
146which may be for a very long time if a client is slow to receive all the data it
147has requested. Here a threading or forking server is appropriate.
148
149In some cases, it may be appropriate to process part of a request synchronously,
150but to finish processing in a forked child depending on the request data. This
151can be implemented by using a synchronous server and doing an explicit fork in
Martin Panter94035f32016-02-19 03:27:46 +0000152the request handler class :meth:`~BaseRequestHandler.handle` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000153
154Another approach to handling multiple simultaneous requests in an environment
Serhiy Storchakab33336f2013-10-13 23:09:00 +0300155that supports neither threads nor :func:`~os.fork` (or where these are too
156expensive or inappropriate for the service) is to maintain an explicit table of
157partially finished requests and to use :func:`~select.select` to decide which
158request to work on next (or whether to handle a new incoming request). This is
159particularly important for stream services where each client can potentially be
160connected for a long time (if threads or subprocesses cannot be used). See
161:mod:`asyncore` for another way to manage this.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000162
Georg Brandlb19be572007-12-29 10:57:00 +0000163.. XXX should data and methods be intermingled, or separate?
164 how should the distinction between class and instance variables be drawn?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000165
166
167Server Objects
168--------------
169
Martin Panter94035f32016-02-19 03:27:46 +0000170.. class:: BaseServer(server_address, RequestHandlerClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171
Georg Brandl9af0c562009-04-05 10:24:20 +0000172 This is the superclass of all Server objects in the module. It defines the
173 interface, given below, but does not implement most of the methods, which is
Martin Panter94035f32016-02-19 03:27:46 +0000174 done in subclasses. The two parameters are stored in the respective
175 :attr:`server_address` and :attr:`RequestHandlerClass` attributes.
Georg Brandl9af0c562009-04-05 10:24:20 +0000176
177
Martin Panter94035f32016-02-19 03:27:46 +0000178 .. method:: fileno()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179
Martin Panter94035f32016-02-19 03:27:46 +0000180 Return an integer file descriptor for the socket on which the server is
181 listening. This function is most commonly passed to :func:`select.select`, to
182 allow monitoring multiple servers in the same process.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000183
184
Martin Panter94035f32016-02-19 03:27:46 +0000185 .. method:: handle_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000186
Martin Panter94035f32016-02-19 03:27:46 +0000187 Process a single request. This function calls the following methods in
188 order: :meth:`get_request`, :meth:`verify_request`, and
189 :meth:`process_request`. If the user-provided
190 :meth:`~BaseRequestHandler.handle` method of the
191 handler class raises an exception, the server's :meth:`handle_error` method
192 will be called. If no request is received within :attr:`timeout`
193 seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
194 will return.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000195
196
Martin Panter94035f32016-02-19 03:27:46 +0000197 .. method:: serve_forever(poll_interval=0.5)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198
Martin Panter94035f32016-02-19 03:27:46 +0000199 Handle requests until an explicit :meth:`shutdown` request. Poll for
200 shutdown every *poll_interval* seconds.
201 Ignores the :attr:`timeout` attribute.
202 If you need to do periodic tasks, do them in another thread.
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000203
204
Martin Panter94035f32016-02-19 03:27:46 +0000205 .. method:: shutdown()
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000206
Martin Panter94035f32016-02-19 03:27:46 +0000207 Tell the :meth:`serve_forever` loop to stop and wait until it does.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000208
Martin Panter94035f32016-02-19 03:27:46 +0000209 .. versionadded:: 2.6
Georg Brandl910df2f2008-06-26 18:55:37 +0000210
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
Martin Panter94035f32016-02-19 03:27:46 +0000212 .. method:: server_close()
Robert Collins2f2c8292015-07-29 12:48:42 +1200213
Martin Panter94035f32016-02-19 03:27:46 +0000214 Clean up the server. May be overridden.
Robert Collins2f2c8292015-07-29 12:48:42 +1200215
Martin Panter94035f32016-02-19 03:27:46 +0000216 .. versionadded:: 2.6
Robert Collins2f2c8292015-07-29 12:48:42 +1200217
218
Martin Panter94035f32016-02-19 03:27:46 +0000219 .. attribute:: address_family
Georg Brandl8ec7f652007-08-15 14:28:01 +0000220
Martin Panter94035f32016-02-19 03:27:46 +0000221 The family of protocols to which the server's socket belongs.
222 Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223
224
Martin Panter94035f32016-02-19 03:27:46 +0000225 .. attribute:: RequestHandlerClass
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226
Martin Panter94035f32016-02-19 03:27:46 +0000227 The user-provided request handler class; an instance of this class is created
228 for each request.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000229
230
Martin Panter94035f32016-02-19 03:27:46 +0000231 .. attribute:: server_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000232
Martin Panter94035f32016-02-19 03:27:46 +0000233 The address on which the server is listening. The format of addresses varies
234 depending on the protocol family;
235 see the documentation for the :mod:`socket` module
236 for details. For Internet protocols, this is a tuple containing a string giving
237 the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000238
239
Martin Panter94035f32016-02-19 03:27:46 +0000240 .. attribute:: socket
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241
Martin Panter94035f32016-02-19 03:27:46 +0000242 The socket object on which the server will listen for incoming requests.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000243
Georg Brandl9af0c562009-04-05 10:24:20 +0000244
Martin Panter94035f32016-02-19 03:27:46 +0000245 The server classes support the following class variables:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246
Martin Panter94035f32016-02-19 03:27:46 +0000247 .. XXX should class variables be covered before instance variables, or vice versa?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000248
Martin Panter94035f32016-02-19 03:27:46 +0000249 .. attribute:: allow_reuse_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000250
Martin Panter94035f32016-02-19 03:27:46 +0000251 Whether the server will allow the reuse of an address. This defaults to
252 :const:`False`, and can be set in subclasses to change the policy.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253
254
Martin Panter94035f32016-02-19 03:27:46 +0000255 .. attribute:: request_queue_size
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256
Martin Panter94035f32016-02-19 03:27:46 +0000257 The size of the request queue. If it takes a long time to process a single
258 request, any requests that arrive while the server is busy are placed into a
259 queue, up to :attr:`request_queue_size` requests. Once the queue is full,
260 further requests from clients will get a "Connection denied" error. The default
261 value is usually 5, but this can be overridden by subclasses.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000262
263
Martin Panter94035f32016-02-19 03:27:46 +0000264 .. attribute:: socket_type
Georg Brandl8ec7f652007-08-15 14:28:01 +0000265
Martin Panter94035f32016-02-19 03:27:46 +0000266 The type of socket used by the server; :const:`socket.SOCK_STREAM` and
267 :const:`socket.SOCK_DGRAM` are two common values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000268
Georg Brandl9af0c562009-04-05 10:24:20 +0000269
Martin Panter94035f32016-02-19 03:27:46 +0000270 .. attribute:: timeout
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000271
Martin Panter94035f32016-02-19 03:27:46 +0000272 Timeout duration, measured in seconds, or :const:`None` if no timeout is
273 desired. If :meth:`handle_request` receives no incoming requests within the
274 timeout period, the :meth:`handle_timeout` method is called.
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000275
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200276
Martin Panter94035f32016-02-19 03:27:46 +0000277 There are various server methods that can be overridden by subclasses of base
278 server classes like :class:`TCPServer`; these methods aren't useful to external
279 users of the server object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000280
Martin Panter94035f32016-02-19 03:27:46 +0000281 .. XXX should the default implementations of these be documented, or should
282 it be assumed that the user will look at SocketServer.py?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
Martin Panter94035f32016-02-19 03:27:46 +0000284 .. method:: finish_request()
285
286 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
287 calling its :meth:`~BaseRequestHandler.handle` method.
288
289
290 .. method:: get_request()
291
292 Must accept a request from the socket, and return a 2-tuple containing the *new*
293 socket object to be used to communicate with the client, and the client's
294 address.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295
Georg Brandl8ec7f652007-08-15 14:28:01 +0000296
Martin Panter94035f32016-02-19 03:27:46 +0000297 .. method:: handle_error(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000298
Martin Panter94035f32016-02-19 03:27:46 +0000299 This function is called if the :meth:`~BaseRequestHandler.handle`
300 method of a :attr:`RequestHandlerClass` instance raises
301 an exception. The default action is to print the traceback to
302 standard output and continue handling further requests.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000303
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304
Martin Panter94035f32016-02-19 03:27:46 +0000305 .. method:: handle_timeout()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306
Martin Panter94035f32016-02-19 03:27:46 +0000307 This function is called when the :attr:`timeout` attribute has been set to a
308 value other than :const:`None` and the timeout period has passed with no
309 requests being received. The default action for forking servers is
310 to collect the status of any child processes that have exited, while
311 in threading servers this method does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000312
Georg Brandl8ec7f652007-08-15 14:28:01 +0000313
Martin Panter94035f32016-02-19 03:27:46 +0000314 .. method:: process_request(request, client_address)
Georg Brandl9af0c562009-04-05 10:24:20 +0000315
Martin Panter94035f32016-02-19 03:27:46 +0000316 Calls :meth:`finish_request` to create an instance of the
317 :attr:`RequestHandlerClass`. If desired, this function can create a new process
318 or thread to handle the request; the :class:`ForkingMixIn` and
319 :class:`ThreadingMixIn` classes do this.
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000320
Georg Brandl8ec7f652007-08-15 14:28:01 +0000321
Martin Panter94035f32016-02-19 03:27:46 +0000322 .. Is there any point in documenting the following two functions?
323 What would the purpose of overriding them be: initializing server
324 instance variables, adding new network families?
Georg Brandl9af0c562009-04-05 10:24:20 +0000325
Martin Panter94035f32016-02-19 03:27:46 +0000326 .. method:: server_activate()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000327
Martin Panter94035f32016-02-19 03:27:46 +0000328 Called by the server's constructor to activate the server. The default behavior
329 for a TCP server just invokes :meth:`~socket.socket.listen`
330 on the server's socket. May be overridden.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000331
Georg Brandl9af0c562009-04-05 10:24:20 +0000332
Martin Panter94035f32016-02-19 03:27:46 +0000333 .. method:: server_bind()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334
Martin Panter94035f32016-02-19 03:27:46 +0000335 Called by the server's constructor to bind the socket to the desired address.
336 May be overridden.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000337
Georg Brandl8ec7f652007-08-15 14:28:01 +0000338
Martin Panter94035f32016-02-19 03:27:46 +0000339 .. method:: verify_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000340
Martin Panter94035f32016-02-19 03:27:46 +0000341 Must return a Boolean value; if the value is :const:`True`, the request will be
342 processed, and if it's :const:`False`, the request will be denied. This function
343 can be overridden to implement access controls for a server. The default
344 implementation always returns :const:`True`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000345
Georg Brandl8ec7f652007-08-15 14:28:01 +0000346
Martin Panter94035f32016-02-19 03:27:46 +0000347Request Handler Objects
348-----------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000349
Martin Panter94035f32016-02-19 03:27:46 +0000350.. class:: BaseRequestHandler
Georg Brandl8ec7f652007-08-15 14:28:01 +0000351
Martin Panter94035f32016-02-19 03:27:46 +0000352 This is the superclass of all request handler objects. It defines
353 the interface, given below. A concrete request handler subclass must
354 define a new :meth:`handle` method, and can override any of
355 the other methods. A new instance of the subclass is created for each
356 request.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000357
358
Martin Panter94035f32016-02-19 03:27:46 +0000359 .. method:: setup()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360
Martin Panter94035f32016-02-19 03:27:46 +0000361 Called before the :meth:`handle` method to perform any initialization actions
362 required. The default implementation does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363
364
Martin Panter94035f32016-02-19 03:27:46 +0000365 .. method:: handle()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000366
Martin Panter94035f32016-02-19 03:27:46 +0000367 This function must do all the work required to service a request. The
368 default implementation does nothing. Several instance attributes are
369 available to it; the request is available as :attr:`self.request`; the client
370 address as :attr:`self.client_address`; and the server instance as
371 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000372
Martin Panter94035f32016-02-19 03:27:46 +0000373 The type of :attr:`self.request` is different for datagram or stream
374 services. For stream services, :attr:`self.request` is a socket object; for
375 datagram services, :attr:`self.request` is a pair of string and socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000376
Georg Brandl8ec7f652007-08-15 14:28:01 +0000377
Martin Panter94035f32016-02-19 03:27:46 +0000378 .. method:: finish()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000379
Martin Panter94035f32016-02-19 03:27:46 +0000380 Called after the :meth:`handle` method to perform any clean-up actions
381 required. The default implementation does nothing. If :meth:`setup`
382 raises an exception, this function will not be called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000383
384
Martin Panter94035f32016-02-19 03:27:46 +0000385.. class:: StreamRequestHandler
386 DatagramRequestHandler
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387
Martin Panter94035f32016-02-19 03:27:46 +0000388 These :class:`BaseRequestHandler` subclasses override the
389 :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish`
390 methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes.
391 The :attr:`self.rfile` and :attr:`self.wfile` attributes can be
392 read or written, respectively, to get the request data or return data
393 to the client.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394
Georg Brandl67d69332008-05-18 08:52:59 +0000395
396Examples
397--------
398
Georg Brandle152a772008-05-24 18:31:28 +0000399:class:`SocketServer.TCPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000400~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
401
402This is the server side::
403
Georg Brandle152a772008-05-24 18:31:28 +0000404 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000405
Georg Brandle152a772008-05-24 18:31:28 +0000406 class MyTCPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000407 """
Martin Panter94035f32016-02-19 03:27:46 +0000408 The request handler class for our server.
Georg Brandl67d69332008-05-18 08:52:59 +0000409
410 It is instantiated once per connection to the server, and must
411 override the handle() method to implement communication to the
412 client.
413 """
414
415 def handle(self):
416 # self.request is the TCP socket connected to the client
417 self.data = self.request.recv(1024).strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200418 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000419 print self.data
420 # just send back the same data, but upper-cased
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800421 self.request.sendall(self.data.upper())
Georg Brandl67d69332008-05-18 08:52:59 +0000422
423 if __name__ == "__main__":
424 HOST, PORT = "localhost", 9999
425
426 # Create the server, binding to localhost on port 9999
Georg Brandle152a772008-05-24 18:31:28 +0000427 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
Georg Brandl67d69332008-05-18 08:52:59 +0000428
429 # Activate the server; this will keep running until you
430 # interrupt the program with Ctrl-C
431 server.serve_forever()
432
433An alternative request handler class that makes use of streams (file-like
434objects that simplify communication by providing the standard file interface)::
435
Georg Brandle152a772008-05-24 18:31:28 +0000436 class MyTCPHandler(SocketServer.StreamRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000437
438 def handle(self):
439 # self.rfile is a file-like object created by the handler;
440 # we can now use e.g. readline() instead of raw recv() calls
441 self.data = self.rfile.readline().strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200442 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000443 print self.data
444 # Likewise, self.wfile is a file-like object used to write back
445 # to the client
446 self.wfile.write(self.data.upper())
447
448The difference is that the ``readline()`` call in the second handler will call
449``recv()`` multiple times until it encounters a newline character, while the
450single ``recv()`` call in the first handler will just return what has been sent
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800451from the client in one ``sendall()`` call.
Georg Brandl67d69332008-05-18 08:52:59 +0000452
453
454This is the client side::
455
456 import socket
457 import sys
458
459 HOST, PORT = "localhost", 9999
460 data = " ".join(sys.argv[1:])
461
462 # Create a socket (SOCK_STREAM means a TCP socket)
463 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
464
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200465 try:
466 # Connect to server and send data
467 sock.connect((HOST, PORT))
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800468 sock.sendall(data + "\n")
Georg Brandl67d69332008-05-18 08:52:59 +0000469
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200470 # Receive data from the server and shut down
471 received = sock.recv(1024)
472 finally:
473 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000474
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200475 print "Sent: {}".format(data)
476 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000477
478
479The output of the example should look something like this:
480
481Server::
482
483 $ python TCPServer.py
484 127.0.0.1 wrote:
485 hello world with TCP
486 127.0.0.1 wrote:
487 python is nice
488
489Client::
490
491 $ python TCPClient.py hello world with TCP
492 Sent: hello world with TCP
493 Received: HELLO WORLD WITH TCP
494 $ python TCPClient.py python is nice
495 Sent: python is nice
496 Received: PYTHON IS NICE
497
498
Georg Brandle152a772008-05-24 18:31:28 +0000499:class:`SocketServer.UDPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000500~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
501
502This is the server side::
503
Georg Brandle152a772008-05-24 18:31:28 +0000504 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000505
Georg Brandle152a772008-05-24 18:31:28 +0000506 class MyUDPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000507 """
508 This class works similar to the TCP handler class, except that
509 self.request consists of a pair of data and client socket, and since
510 there is no connection the client address must be given explicitly
511 when sending data back via sendto().
512 """
513
514 def handle(self):
515 data = self.request[0].strip()
516 socket = self.request[1]
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200517 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000518 print data
519 socket.sendto(data.upper(), self.client_address)
520
521 if __name__ == "__main__":
R. David Murray48239612009-11-20 13:29:43 +0000522 HOST, PORT = "localhost", 9999
523 server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
524 server.serve_forever()
Georg Brandl67d69332008-05-18 08:52:59 +0000525
526This is the client side::
527
528 import socket
529 import sys
530
Georg Brandle8ddbec2009-08-24 17:22:05 +0000531 HOST, PORT = "localhost", 9999
Georg Brandl67d69332008-05-18 08:52:59 +0000532 data = " ".join(sys.argv[1:])
533
534 # SOCK_DGRAM is the socket type to use for UDP sockets
535 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
536
537 # As you can see, there is no connect() call; UDP has no connections.
538 # Instead, data is directly sent to the recipient via sendto().
539 sock.sendto(data + "\n", (HOST, PORT))
540 received = sock.recv(1024)
541
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200542 print "Sent: {}".format(data)
543 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000544
545The output of the example should look exactly like for the TCP server example.
546
547
548Asynchronous Mixins
549~~~~~~~~~~~~~~~~~~~
550
551To build asynchronous handlers, use the :class:`ThreadingMixIn` and
552:class:`ForkingMixIn` classes.
553
554An example for the :class:`ThreadingMixIn` class::
555
556 import socket
557 import threading
Georg Brandle152a772008-05-24 18:31:28 +0000558 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000559
Georg Brandle152a772008-05-24 18:31:28 +0000560 class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000561
562 def handle(self):
563 data = self.request.recv(1024)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200564 cur_thread = threading.current_thread()
565 response = "{}: {}".format(cur_thread.name, data)
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800566 self.request.sendall(response)
Georg Brandl67d69332008-05-18 08:52:59 +0000567
Georg Brandle152a772008-05-24 18:31:28 +0000568 class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
Georg Brandl67d69332008-05-18 08:52:59 +0000569 pass
570
571 def client(ip, port, message):
572 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
573 sock.connect((ip, port))
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200574 try:
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800575 sock.sendall(message)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200576 response = sock.recv(1024)
577 print "Received: {}".format(response)
578 finally:
579 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000580
581 if __name__ == "__main__":
582 # Port 0 means to select an arbitrary unused port
583 HOST, PORT = "localhost", 0
584
585 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
586 ip, port = server.server_address
587
588 # Start a thread with the server -- that thread will then start one
589 # more thread for each request
590 server_thread = threading.Thread(target=server.serve_forever)
591 # Exit the server thread when the main thread terminates
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200592 server_thread.daemon = True
Georg Brandl67d69332008-05-18 08:52:59 +0000593 server_thread.start()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200594 print "Server loop running in thread:", server_thread.name
Georg Brandl67d69332008-05-18 08:52:59 +0000595
596 client(ip, port, "Hello World 1")
597 client(ip, port, "Hello World 2")
598 client(ip, port, "Hello World 3")
599
600 server.shutdown()
Robert Collins2f2c8292015-07-29 12:48:42 +1200601 server.server_close()
Georg Brandl67d69332008-05-18 08:52:59 +0000602
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200603
Georg Brandl67d69332008-05-18 08:52:59 +0000604The output of the example should look something like this::
605
606 $ python ThreadedTCPServer.py
607 Server loop running in thread: Thread-1
608 Received: Thread-2: Hello World 1
609 Received: Thread-3: Hello World 2
610 Received: Thread-4: Hello World 3
611
612
613The :class:`ForkingMixIn` class is used in the same way, except that the server
614will spawn a new process for each request.