blob: c34b486806670ea243311d78ebef47b3651a1498 [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
19There are four basic server classes: :class:`TCPServer` uses the Internet TCP
20protocol, which provides for continuous streams of data between the client and
21server. :class:`UDPServer` uses datagrams, which are discrete packets of
22information that may arrive out of order or be lost while in transit. The more
23infrequently used :class:`UnixStreamServer` and :class:`UnixDatagramServer`
24classes are similar, but use Unix domain sockets; they're not available on
25non-Unix platforms. For more details on network programming, consult a book
26such as
27W. Richard Steven's UNIX Network Programming or Ralph Davis's Win32 Network
28Programming.
29
30These four classes process requests :dfn:`synchronously`; each request must be
31completed before the next request can be started. This isn't suitable if each
32request takes a long time to complete, because it requires a lot of computation,
33or because it returns a lot of data which the client is slow to process. The
34solution is to create a separate process or thread to handle each request; the
35:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes can be used to
36support asynchronous behaviour.
37
38Creating a server requires several steps. First, you must create a request
39handler class by subclassing the :class:`BaseRequestHandler` class and
40overriding its :meth:`handle` method; this method will process incoming
41requests. Second, you must instantiate one of the server classes, passing it
42the server's address and the request handler class. Finally, call the
43:meth:`handle_request` or :meth:`serve_forever` method of the server object to
44process one or many requests.
45
46When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
47you should explicitly declare how you want your threads to behave on an abrupt
48shutdown. The :class:`ThreadingMixIn` class defines an attribute
49*daemon_threads*, which indicates whether or not the server should wait for
50thread termination. You should set the flag explicitly if you would like threads
51to behave autonomously; the default is :const:`False`, meaning that Python will
52not exit until all threads created by :class:`ThreadingMixIn` have exited.
53
54Server classes have the same external methods and attributes, no matter what
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +000055network protocol they use.
Georg Brandl8ec7f652007-08-15 14:28:01 +000056
57
58Server Creation Notes
59---------------------
60
61There are five classes in an inheritance diagram, four of which represent
62synchronous servers of four types::
63
64 +------------+
65 | BaseServer |
66 +------------+
67 |
68 v
69 +-----------+ +------------------+
70 | TCPServer |------->| UnixStreamServer |
71 +-----------+ +------------------+
72 |
73 v
74 +-----------+ +--------------------+
75 | UDPServer |------->| UnixDatagramServer |
76 +-----------+ +--------------------+
77
78Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
79:class:`UnixStreamServer` --- the only difference between an IP and a Unix
80stream server is the address family, which is simply repeated in both Unix
81server classes.
82
83Forking and threading versions of each type of server can be created using the
84:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes. For instance,
85a threading UDP server class is created as follows::
86
87 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
88
89The mix-in class must come first, since it overrides a method defined in
Senthil Kumaran6f18b982011-07-04 12:50:02 -070090:class:`UDPServer`. Setting the various attributes also change the
Georg Brandl8ec7f652007-08-15 14:28:01 +000091behavior of the underlying server mechanism.
92
93To implement a service, you must derive a class from :class:`BaseRequestHandler`
94and redefine its :meth:`handle` method. You can then run various versions of
95the service by combining one of the server classes with your request handler
96class. The request handler class must be different for datagram or stream
97services. This can be hidden by using the handler subclasses
98:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
99
100Of course, you still have to use your head! For instance, it makes no sense to
101use a forking server if the service contains state in memory that can be
102modified by different requests, since the modifications in the child process
103would never reach the initial state kept in the parent process and passed to
104each child. In this case, you can use a threading server, but you will probably
105have to use locks to protect the integrity of the shared data.
106
107On the other hand, if you are building an HTTP server where all data is stored
108externally (for instance, in the file system), a synchronous class will
109essentially render the service "deaf" while one request is being handled --
110which may be for a very long time if a client is slow to receive all the data it
111has requested. Here a threading or forking server is appropriate.
112
113In some cases, it may be appropriate to process part of a request synchronously,
114but to finish processing in a forked child depending on the request data. This
115can be implemented by using a synchronous server and doing an explicit fork in
116the request handler class :meth:`handle` method.
117
118Another approach to handling multiple simultaneous requests in an environment
119that supports neither threads nor :func:`fork` (or where these are too expensive
120or inappropriate for the service) is to maintain an explicit table of partially
121finished requests and to use :func:`select` to decide which request to work on
122next (or whether to handle a new incoming request). This is particularly
123important for stream services where each client can potentially be connected for
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000124a long time (if threads or subprocesses cannot be used). See :mod:`asyncore` for
125another way to manage this.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000126
Georg Brandlb19be572007-12-29 10:57:00 +0000127.. XXX should data and methods be intermingled, or separate?
128 how should the distinction between class and instance variables be drawn?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000129
130
131Server Objects
132--------------
133
Georg Brandl9af0c562009-04-05 10:24:20 +0000134.. class:: BaseServer
Georg Brandl8ec7f652007-08-15 14:28:01 +0000135
Georg Brandl9af0c562009-04-05 10:24:20 +0000136 This is the superclass of all Server objects in the module. It defines the
137 interface, given below, but does not implement most of the methods, which is
138 done in subclasses.
139
140
141.. method:: BaseServer.fileno()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142
143 Return an integer file descriptor for the socket on which the server is
144 listening. This function is most commonly passed to :func:`select.select`, to
145 allow monitoring multiple servers in the same process.
146
147
Georg Brandl9af0c562009-04-05 10:24:20 +0000148.. method:: BaseServer.handle_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000150 Process a single request. This function calls the following methods in
151 order: :meth:`get_request`, :meth:`verify_request`, and
152 :meth:`process_request`. If the user-provided :meth:`handle` method of the
153 handler class raises an exception, the server's :meth:`handle_error` method
154 will be called. If no request is received within :attr:`self.timeout`
155 seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
156 will return.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157
158
Georg Brandl9af0c562009-04-05 10:24:20 +0000159.. method:: BaseServer.serve_forever(poll_interval=0.5)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
Sandro Tosi499718d2012-01-03 22:35:41 +0100161 Handle requests until an explicit :meth:`shutdown` request.
162 Poll for shutdown every *poll_interval* seconds. Ignores :attr:`self.timeout`.
163 If you need to do periodic tasks, do them in another thread.
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000164
165
Georg Brandl9af0c562009-04-05 10:24:20 +0000166.. method:: BaseServer.shutdown()
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000167
Sandro Tosi499718d2012-01-03 22:35:41 +0100168 Tell the :meth:`serve_forever` loop to stop and wait until it does.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169
Georg Brandl910df2f2008-06-26 18:55:37 +0000170 .. versionadded:: 2.6
171
Georg Brandl8ec7f652007-08-15 14:28:01 +0000172
Georg Brandl9af0c562009-04-05 10:24:20 +0000173.. attribute:: BaseServer.address_family
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
175 The family of protocols to which the server's socket belongs.
Georg Brandl0aaf5592008-05-11 10:59:39 +0000176 Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000177
178
Georg Brandl9af0c562009-04-05 10:24:20 +0000179.. attribute:: BaseServer.RequestHandlerClass
Georg Brandl8ec7f652007-08-15 14:28:01 +0000180
181 The user-provided request handler class; an instance of this class is created
182 for each request.
183
184
Georg Brandl9af0c562009-04-05 10:24:20 +0000185.. attribute:: BaseServer.server_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000186
187 The address on which the server is listening. The format of addresses varies
188 depending on the protocol family; see the documentation for the socket module
189 for details. For Internet protocols, this is a tuple containing a string giving
190 the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
191
192
Georg Brandl9af0c562009-04-05 10:24:20 +0000193.. attribute:: BaseServer.socket
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
195 The socket object on which the server will listen for incoming requests.
196
Georg Brandl9af0c562009-04-05 10:24:20 +0000197
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198The server classes support the following class variables:
199
Georg Brandlb19be572007-12-29 10:57:00 +0000200.. XXX should class variables be covered before instance variables, or vice versa?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000201
Georg Brandl9af0c562009-04-05 10:24:20 +0000202.. attribute:: BaseServer.allow_reuse_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203
204 Whether the server will allow the reuse of an address. This defaults to
205 :const:`False`, and can be set in subclasses to change the policy.
206
207
Georg Brandl9af0c562009-04-05 10:24:20 +0000208.. attribute:: BaseServer.request_queue_size
Georg Brandl8ec7f652007-08-15 14:28:01 +0000209
210 The size of the request queue. If it takes a long time to process a single
211 request, any requests that arrive while the server is busy are placed into a
212 queue, up to :attr:`request_queue_size` requests. Once the queue is full,
213 further requests from clients will get a "Connection denied" error. The default
214 value is usually 5, but this can be overridden by subclasses.
215
216
Georg Brandl9af0c562009-04-05 10:24:20 +0000217.. attribute:: BaseServer.socket_type
Georg Brandl8ec7f652007-08-15 14:28:01 +0000218
219 The type of socket used by the server; :const:`socket.SOCK_STREAM` and
Georg Brandl0aaf5592008-05-11 10:59:39 +0000220 :const:`socket.SOCK_DGRAM` are two common values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000221
Georg Brandl9af0c562009-04-05 10:24:20 +0000222
223.. attribute:: BaseServer.timeout
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000224
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000225 Timeout duration, measured in seconds, or :const:`None` if no timeout is
226 desired. If :meth:`handle_request` receives no incoming requests within the
227 timeout period, the :meth:`handle_timeout` method is called.
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000228
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200229
Georg Brandl8ec7f652007-08-15 14:28:01 +0000230There are various server methods that can be overridden by subclasses of base
231server classes like :class:`TCPServer`; these methods aren't useful to external
232users of the server object.
233
Georg Brandlb19be572007-12-29 10:57:00 +0000234.. XXX should the default implementations of these be documented, or should
Georg Brandle152a772008-05-24 18:31:28 +0000235 it be assumed that the user will look at SocketServer.py?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000236
Georg Brandl9af0c562009-04-05 10:24:20 +0000237.. method:: BaseServer.finish_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000238
239 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
240 calling its :meth:`handle` method.
241
242
Georg Brandl9af0c562009-04-05 10:24:20 +0000243.. method:: BaseServer.get_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
245 Must accept a request from the socket, and return a 2-tuple containing the *new*
246 socket object to be used to communicate with the client, and the client's
247 address.
248
249
Georg Brandl9af0c562009-04-05 10:24:20 +0000250.. method:: BaseServer.handle_error(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251
252 This function is called if the :attr:`RequestHandlerClass`'s :meth:`handle`
253 method raises an exception. The default action is to print the traceback to
254 standard output and continue handling further requests.
255
Georg Brandl9af0c562009-04-05 10:24:20 +0000256
257.. method:: BaseServer.handle_timeout()
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000258
Georg Brandl67d69332008-05-18 08:52:59 +0000259 This function is called when the :attr:`timeout` attribute has been set to a
260 value other than :const:`None` and the timeout period has passed with no
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000261 requests being received. The default action for forking servers is
262 to collect the status of any child processes that have exited, while
263 in threading servers this method does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000264
Georg Brandl9af0c562009-04-05 10:24:20 +0000265
266.. method:: BaseServer.process_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000267
268 Calls :meth:`finish_request` to create an instance of the
269 :attr:`RequestHandlerClass`. If desired, this function can create a new process
270 or thread to handle the request; the :class:`ForkingMixIn` and
271 :class:`ThreadingMixIn` classes do this.
272
Georg Brandl9af0c562009-04-05 10:24:20 +0000273
Georg Brandlb19be572007-12-29 10:57:00 +0000274.. Is there any point in documenting the following two functions?
275 What would the purpose of overriding them be: initializing server
276 instance variables, adding new network families?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
Georg Brandl9af0c562009-04-05 10:24:20 +0000278.. method:: BaseServer.server_activate()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279
280 Called by the server's constructor to activate the server. The default behavior
281 just :meth:`listen`\ s to the server's socket. May be overridden.
282
283
Georg Brandl9af0c562009-04-05 10:24:20 +0000284.. method:: BaseServer.server_bind()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285
286 Called by the server's constructor to bind the socket to the desired address.
287 May be overridden.
288
289
Georg Brandl9af0c562009-04-05 10:24:20 +0000290.. method:: BaseServer.verify_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291
292 Must return a Boolean value; if the value is :const:`True`, the request will be
293 processed, and if it's :const:`False`, the request will be denied. This function
294 can be overridden to implement access controls for a server. The default
295 implementation always returns :const:`True`.
296
297
298RequestHandler Objects
299----------------------
300
301The request handler class must define a new :meth:`handle` method, and can
302override any of the following methods. A new instance is created for each
303request.
304
305
Georg Brandl9af0c562009-04-05 10:24:20 +0000306.. method:: RequestHandler.finish()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307
Georg Brandl67d69332008-05-18 08:52:59 +0000308 Called after the :meth:`handle` method to perform any clean-up actions
309 required. The default implementation does nothing. If :meth:`setup` or
310 :meth:`handle` raise an exception, this function will not be called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000311
312
Georg Brandl9af0c562009-04-05 10:24:20 +0000313.. method:: RequestHandler.handle()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314
Georg Brandl67d69332008-05-18 08:52:59 +0000315 This function must do all the work required to service a request. The
316 default implementation does nothing. Several instance attributes are
317 available to it; the request is available as :attr:`self.request`; the client
318 address as :attr:`self.client_address`; and the server instance as
319 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320
Georg Brandl67d69332008-05-18 08:52:59 +0000321 The type of :attr:`self.request` is different for datagram or stream
322 services. For stream services, :attr:`self.request` is a socket object; for
323 datagram services, :attr:`self.request` is a pair of string and socket.
324 However, this can be hidden by using the request handler subclasses
325 :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which
326 override the :meth:`setup` and :meth:`finish` methods, and provide
327 :attr:`self.rfile` and :attr:`self.wfile` attributes. :attr:`self.rfile` and
328 :attr:`self.wfile` can be read or written, respectively, to get the request
329 data or return data to the client.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000330
331
Georg Brandl9af0c562009-04-05 10:24:20 +0000332.. method:: RequestHandler.setup()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000333
334 Called before the :meth:`handle` method to perform any initialization actions
335 required. The default implementation does nothing.
336
Georg Brandl67d69332008-05-18 08:52:59 +0000337
338Examples
339--------
340
Georg Brandle152a772008-05-24 18:31:28 +0000341:class:`SocketServer.TCPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000342~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
343
344This is the server side::
345
Georg Brandle152a772008-05-24 18:31:28 +0000346 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000347
Georg Brandle152a772008-05-24 18:31:28 +0000348 class MyTCPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000349 """
350 The RequestHandler class for our server.
351
352 It is instantiated once per connection to the server, and must
353 override the handle() method to implement communication to the
354 client.
355 """
356
357 def handle(self):
358 # self.request is the TCP socket connected to the client
359 self.data = self.request.recv(1024).strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200360 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000361 print self.data
362 # just send back the same data, but upper-cased
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800363 self.request.sendall(self.data.upper())
Georg Brandl67d69332008-05-18 08:52:59 +0000364
365 if __name__ == "__main__":
366 HOST, PORT = "localhost", 9999
367
368 # Create the server, binding to localhost on port 9999
Georg Brandle152a772008-05-24 18:31:28 +0000369 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
Georg Brandl67d69332008-05-18 08:52:59 +0000370
371 # Activate the server; this will keep running until you
372 # interrupt the program with Ctrl-C
373 server.serve_forever()
374
375An alternative request handler class that makes use of streams (file-like
376objects that simplify communication by providing the standard file interface)::
377
Georg Brandle152a772008-05-24 18:31:28 +0000378 class MyTCPHandler(SocketServer.StreamRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000379
380 def handle(self):
381 # self.rfile is a file-like object created by the handler;
382 # we can now use e.g. readline() instead of raw recv() calls
383 self.data = self.rfile.readline().strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200384 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000385 print self.data
386 # Likewise, self.wfile is a file-like object used to write back
387 # to the client
388 self.wfile.write(self.data.upper())
389
390The difference is that the ``readline()`` call in the second handler will call
391``recv()`` multiple times until it encounters a newline character, while the
392single ``recv()`` call in the first handler will just return what has been sent
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800393from the client in one ``sendall()`` call.
Georg Brandl67d69332008-05-18 08:52:59 +0000394
395
396This is the client side::
397
398 import socket
399 import sys
400
401 HOST, PORT = "localhost", 9999
402 data = " ".join(sys.argv[1:])
403
404 # Create a socket (SOCK_STREAM means a TCP socket)
405 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
406
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200407 try:
408 # Connect to server and send data
409 sock.connect((HOST, PORT))
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800410 sock.sendall(data + "\n")
Georg Brandl67d69332008-05-18 08:52:59 +0000411
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200412 # Receive data from the server and shut down
413 received = sock.recv(1024)
414 finally:
415 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000416
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200417 print "Sent: {}".format(data)
418 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000419
420
421The output of the example should look something like this:
422
423Server::
424
425 $ python TCPServer.py
426 127.0.0.1 wrote:
427 hello world with TCP
428 127.0.0.1 wrote:
429 python is nice
430
431Client::
432
433 $ python TCPClient.py hello world with TCP
434 Sent: hello world with TCP
435 Received: HELLO WORLD WITH TCP
436 $ python TCPClient.py python is nice
437 Sent: python is nice
438 Received: PYTHON IS NICE
439
440
Georg Brandle152a772008-05-24 18:31:28 +0000441:class:`SocketServer.UDPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000442~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
443
444This is the server side::
445
Georg Brandle152a772008-05-24 18:31:28 +0000446 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000447
Georg Brandle152a772008-05-24 18:31:28 +0000448 class MyUDPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000449 """
450 This class works similar to the TCP handler class, except that
451 self.request consists of a pair of data and client socket, and since
452 there is no connection the client address must be given explicitly
453 when sending data back via sendto().
454 """
455
456 def handle(self):
457 data = self.request[0].strip()
458 socket = self.request[1]
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200459 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000460 print data
461 socket.sendto(data.upper(), self.client_address)
462
463 if __name__ == "__main__":
R. David Murray48239612009-11-20 13:29:43 +0000464 HOST, PORT = "localhost", 9999
465 server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
466 server.serve_forever()
Georg Brandl67d69332008-05-18 08:52:59 +0000467
468This is the client side::
469
470 import socket
471 import sys
472
Georg Brandle8ddbec2009-08-24 17:22:05 +0000473 HOST, PORT = "localhost", 9999
Georg Brandl67d69332008-05-18 08:52:59 +0000474 data = " ".join(sys.argv[1:])
475
476 # SOCK_DGRAM is the socket type to use for UDP sockets
477 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
478
479 # As you can see, there is no connect() call; UDP has no connections.
480 # Instead, data is directly sent to the recipient via sendto().
481 sock.sendto(data + "\n", (HOST, PORT))
482 received = sock.recv(1024)
483
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200484 print "Sent: {}".format(data)
485 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000486
487The output of the example should look exactly like for the TCP server example.
488
489
490Asynchronous Mixins
491~~~~~~~~~~~~~~~~~~~
492
493To build asynchronous handlers, use the :class:`ThreadingMixIn` and
494:class:`ForkingMixIn` classes.
495
496An example for the :class:`ThreadingMixIn` class::
497
498 import socket
499 import threading
Georg Brandle152a772008-05-24 18:31:28 +0000500 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000501
Georg Brandle152a772008-05-24 18:31:28 +0000502 class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000503
504 def handle(self):
505 data = self.request.recv(1024)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200506 cur_thread = threading.current_thread()
507 response = "{}: {}".format(cur_thread.name, data)
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800508 self.request.sendall(response)
Georg Brandl67d69332008-05-18 08:52:59 +0000509
Georg Brandle152a772008-05-24 18:31:28 +0000510 class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
Georg Brandl67d69332008-05-18 08:52:59 +0000511 pass
512
513 def client(ip, port, message):
514 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
515 sock.connect((ip, port))
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200516 try:
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800517 sock.sendall(message)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200518 response = sock.recv(1024)
519 print "Received: {}".format(response)
520 finally:
521 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000522
523 if __name__ == "__main__":
524 # Port 0 means to select an arbitrary unused port
525 HOST, PORT = "localhost", 0
526
527 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
528 ip, port = server.server_address
529
530 # Start a thread with the server -- that thread will then start one
531 # more thread for each request
532 server_thread = threading.Thread(target=server.serve_forever)
533 # Exit the server thread when the main thread terminates
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200534 server_thread.daemon = True
Georg Brandl67d69332008-05-18 08:52:59 +0000535 server_thread.start()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200536 print "Server loop running in thread:", server_thread.name
Georg Brandl67d69332008-05-18 08:52:59 +0000537
538 client(ip, port, "Hello World 1")
539 client(ip, port, "Hello World 2")
540 client(ip, port, "Hello World 3")
541
542 server.shutdown()
543
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200544
Georg Brandl67d69332008-05-18 08:52:59 +0000545The output of the example should look something like this::
546
547 $ python ThreadedTCPServer.py
548 Server loop running in thread: Thread-1
549 Received: Thread-2: Hello World 1
550 Received: Thread-3: Hello World 2
551 Received: Thread-4: Hello World 3
552
553
554The :class:`ForkingMixIn` class is used in the same way, except that the server
555will spawn a new process for each request.