blob: 4c48267b0aefa8a0445dc283d7a8e437aeb3ae8a [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
10 Python 3.0. The :term:`2to3` tool will automatically adapt imports when
11 converting your sources to 3.0.
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
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000161 Handle requests until an explicit :meth:`shutdown` request. Polls for
162 shutdown every *poll_interval* seconds.
163
164
Georg Brandl9af0c562009-04-05 10:24:20 +0000165.. method:: BaseServer.shutdown()
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000166
167 Tells the :meth:`serve_forever` loop to stop and waits until it does.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000168
Georg Brandl910df2f2008-06-26 18:55:37 +0000169 .. versionadded:: 2.6
170
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171
Georg Brandl9af0c562009-04-05 10:24:20 +0000172.. attribute:: BaseServer.address_family
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173
174 The family of protocols to which the server's socket belongs.
Georg Brandl0aaf5592008-05-11 10:59:39 +0000175 Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000176
177
Georg Brandl9af0c562009-04-05 10:24:20 +0000178.. attribute:: BaseServer.RequestHandlerClass
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179
180 The user-provided request handler class; an instance of this class is created
181 for each request.
182
183
Georg Brandl9af0c562009-04-05 10:24:20 +0000184.. attribute:: BaseServer.server_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185
186 The address on which the server is listening. The format of addresses varies
187 depending on the protocol family; see the documentation for the socket module
188 for details. For Internet protocols, this is a tuple containing a string giving
189 the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
190
191
Georg Brandl9af0c562009-04-05 10:24:20 +0000192.. attribute:: BaseServer.socket
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
194 The socket object on which the server will listen for incoming requests.
195
Georg Brandl9af0c562009-04-05 10:24:20 +0000196
Georg Brandl8ec7f652007-08-15 14:28:01 +0000197The server classes support the following class variables:
198
Georg Brandlb19be572007-12-29 10:57:00 +0000199.. XXX should class variables be covered before instance variables, or vice versa?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000200
Georg Brandl9af0c562009-04-05 10:24:20 +0000201.. attribute:: BaseServer.allow_reuse_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
203 Whether the server will allow the reuse of an address. This defaults to
204 :const:`False`, and can be set in subclasses to change the policy.
205
206
Georg Brandl9af0c562009-04-05 10:24:20 +0000207.. attribute:: BaseServer.request_queue_size
Georg Brandl8ec7f652007-08-15 14:28:01 +0000208
209 The size of the request queue. If it takes a long time to process a single
210 request, any requests that arrive while the server is busy are placed into a
211 queue, up to :attr:`request_queue_size` requests. Once the queue is full,
212 further requests from clients will get a "Connection denied" error. The default
213 value is usually 5, but this can be overridden by subclasses.
214
215
Georg Brandl9af0c562009-04-05 10:24:20 +0000216.. attribute:: BaseServer.socket_type
Georg Brandl8ec7f652007-08-15 14:28:01 +0000217
218 The type of socket used by the server; :const:`socket.SOCK_STREAM` and
Georg Brandl0aaf5592008-05-11 10:59:39 +0000219 :const:`socket.SOCK_DGRAM` are two common values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000220
Georg Brandl9af0c562009-04-05 10:24:20 +0000221
222.. attribute:: BaseServer.timeout
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000223
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000224 Timeout duration, measured in seconds, or :const:`None` if no timeout is
225 desired. If :meth:`handle_request` receives no incoming requests within the
226 timeout period, the :meth:`handle_timeout` method is called.
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000227
Georg Brandl8ec7f652007-08-15 14:28:01 +0000228There are various server methods that can be overridden by subclasses of base
229server classes like :class:`TCPServer`; these methods aren't useful to external
230users of the server object.
231
Georg Brandlb19be572007-12-29 10:57:00 +0000232.. XXX should the default implementations of these be documented, or should
Georg Brandle152a772008-05-24 18:31:28 +0000233 it be assumed that the user will look at SocketServer.py?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000234
Georg Brandl9af0c562009-04-05 10:24:20 +0000235.. method:: BaseServer.finish_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000236
237 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
238 calling its :meth:`handle` method.
239
240
Georg Brandl9af0c562009-04-05 10:24:20 +0000241.. method:: BaseServer.get_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242
243 Must accept a request from the socket, and return a 2-tuple containing the *new*
244 socket object to be used to communicate with the client, and the client's
245 address.
246
247
Georg Brandl9af0c562009-04-05 10:24:20 +0000248.. method:: BaseServer.handle_error(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000249
250 This function is called if the :attr:`RequestHandlerClass`'s :meth:`handle`
251 method raises an exception. The default action is to print the traceback to
252 standard output and continue handling further requests.
253
Georg Brandl9af0c562009-04-05 10:24:20 +0000254
255.. method:: BaseServer.handle_timeout()
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000256
Georg Brandl67d69332008-05-18 08:52:59 +0000257 This function is called when the :attr:`timeout` attribute has been set to a
258 value other than :const:`None` and the timeout period has passed with no
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000259 requests being received. The default action for forking servers is
260 to collect the status of any child processes that have exited, while
261 in threading servers this method does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000262
Georg Brandl9af0c562009-04-05 10:24:20 +0000263
264.. method:: BaseServer.process_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000265
266 Calls :meth:`finish_request` to create an instance of the
267 :attr:`RequestHandlerClass`. If desired, this function can create a new process
268 or thread to handle the request; the :class:`ForkingMixIn` and
269 :class:`ThreadingMixIn` classes do this.
270
Georg Brandl9af0c562009-04-05 10:24:20 +0000271
Georg Brandlb19be572007-12-29 10:57:00 +0000272.. Is there any point in documenting the following two functions?
273 What would the purpose of overriding them be: initializing server
274 instance variables, adding new network families?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275
Georg Brandl9af0c562009-04-05 10:24:20 +0000276.. method:: BaseServer.server_activate()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
278 Called by the server's constructor to activate the server. The default behavior
279 just :meth:`listen`\ s to the server's socket. May be overridden.
280
281
Georg Brandl9af0c562009-04-05 10:24:20 +0000282.. method:: BaseServer.server_bind()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
284 Called by the server's constructor to bind the socket to the desired address.
285 May be overridden.
286
287
Georg Brandl9af0c562009-04-05 10:24:20 +0000288.. method:: BaseServer.verify_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000289
290 Must return a Boolean value; if the value is :const:`True`, the request will be
291 processed, and if it's :const:`False`, the request will be denied. This function
292 can be overridden to implement access controls for a server. The default
293 implementation always returns :const:`True`.
294
295
296RequestHandler Objects
297----------------------
298
299The request handler class must define a new :meth:`handle` method, and can
300override any of the following methods. A new instance is created for each
301request.
302
303
Georg Brandl9af0c562009-04-05 10:24:20 +0000304.. method:: RequestHandler.finish()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000305
Georg Brandl67d69332008-05-18 08:52:59 +0000306 Called after the :meth:`handle` method to perform any clean-up actions
307 required. The default implementation does nothing. If :meth:`setup` or
308 :meth:`handle` raise an exception, this function will not be called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000309
310
Georg Brandl9af0c562009-04-05 10:24:20 +0000311.. method:: RequestHandler.handle()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000312
Georg Brandl67d69332008-05-18 08:52:59 +0000313 This function must do all the work required to service a request. The
314 default implementation does nothing. Several instance attributes are
315 available to it; the request is available as :attr:`self.request`; the client
316 address as :attr:`self.client_address`; and the server instance as
317 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000318
Georg Brandl67d69332008-05-18 08:52:59 +0000319 The type of :attr:`self.request` is different for datagram or stream
320 services. For stream services, :attr:`self.request` is a socket object; for
321 datagram services, :attr:`self.request` is a pair of string and socket.
322 However, this can be hidden by using the request handler subclasses
323 :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which
324 override the :meth:`setup` and :meth:`finish` methods, and provide
325 :attr:`self.rfile` and :attr:`self.wfile` attributes. :attr:`self.rfile` and
326 :attr:`self.wfile` can be read or written, respectively, to get the request
327 data or return data to the client.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000328
329
Georg Brandl9af0c562009-04-05 10:24:20 +0000330.. method:: RequestHandler.setup()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000331
332 Called before the :meth:`handle` method to perform any initialization actions
333 required. The default implementation does nothing.
334
Georg Brandl67d69332008-05-18 08:52:59 +0000335
336Examples
337--------
338
Georg Brandle152a772008-05-24 18:31:28 +0000339:class:`SocketServer.TCPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000340~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
341
342This is the server side::
343
Georg Brandle152a772008-05-24 18:31:28 +0000344 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000345
Georg Brandle152a772008-05-24 18:31:28 +0000346 class MyTCPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000347 """
348 The RequestHandler class for our server.
349
350 It is instantiated once per connection to the server, and must
351 override the handle() method to implement communication to the
352 client.
353 """
354
355 def handle(self):
356 # self.request is the TCP socket connected to the client
357 self.data = self.request.recv(1024).strip()
358 print "%s wrote:" % self.client_address[0]
359 print self.data
360 # just send back the same data, but upper-cased
361 self.request.send(self.data.upper())
362
363 if __name__ == "__main__":
364 HOST, PORT = "localhost", 9999
365
366 # Create the server, binding to localhost on port 9999
Georg Brandle152a772008-05-24 18:31:28 +0000367 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
Georg Brandl67d69332008-05-18 08:52:59 +0000368
369 # Activate the server; this will keep running until you
370 # interrupt the program with Ctrl-C
371 server.serve_forever()
372
373An alternative request handler class that makes use of streams (file-like
374objects that simplify communication by providing the standard file interface)::
375
Georg Brandle152a772008-05-24 18:31:28 +0000376 class MyTCPHandler(SocketServer.StreamRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000377
378 def handle(self):
379 # self.rfile is a file-like object created by the handler;
380 # we can now use e.g. readline() instead of raw recv() calls
381 self.data = self.rfile.readline().strip()
382 print "%s wrote:" % self.client_address[0]
383 print self.data
384 # Likewise, self.wfile is a file-like object used to write back
385 # to the client
386 self.wfile.write(self.data.upper())
387
388The difference is that the ``readline()`` call in the second handler will call
389``recv()`` multiple times until it encounters a newline character, while the
390single ``recv()`` call in the first handler will just return what has been sent
391from the client in one ``send()`` call.
392
393
394This is the client side::
395
396 import socket
397 import sys
398
399 HOST, PORT = "localhost", 9999
400 data = " ".join(sys.argv[1:])
401
402 # Create a socket (SOCK_STREAM means a TCP socket)
403 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
404
405 # Connect to server and send data
406 sock.connect((HOST, PORT))
407 sock.send(data + "\n")
408
409 # Receive data from the server and shut down
410 received = sock.recv(1024)
411 sock.close()
412
413 print "Sent: %s" % data
414 print "Received: %s" % received
415
416
417The output of the example should look something like this:
418
419Server::
420
421 $ python TCPServer.py
422 127.0.0.1 wrote:
423 hello world with TCP
424 127.0.0.1 wrote:
425 python is nice
426
427Client::
428
429 $ python TCPClient.py hello world with TCP
430 Sent: hello world with TCP
431 Received: HELLO WORLD WITH TCP
432 $ python TCPClient.py python is nice
433 Sent: python is nice
434 Received: PYTHON IS NICE
435
436
Georg Brandle152a772008-05-24 18:31:28 +0000437:class:`SocketServer.UDPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000438~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
439
440This is the server side::
441
Georg Brandle152a772008-05-24 18:31:28 +0000442 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000443
Georg Brandle152a772008-05-24 18:31:28 +0000444 class MyUDPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000445 """
446 This class works similar to the TCP handler class, except that
447 self.request consists of a pair of data and client socket, and since
448 there is no connection the client address must be given explicitly
449 when sending data back via sendto().
450 """
451
452 def handle(self):
453 data = self.request[0].strip()
454 socket = self.request[1]
455 print "%s wrote:" % self.client_address[0]
456 print data
457 socket.sendto(data.upper(), self.client_address)
458
459 if __name__ == "__main__":
R. David Murray48239612009-11-20 13:29:43 +0000460 HOST, PORT = "localhost", 9999
461 server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
462 server.serve_forever()
Georg Brandl67d69332008-05-18 08:52:59 +0000463
464This is the client side::
465
466 import socket
467 import sys
468
Georg Brandle8ddbec2009-08-24 17:22:05 +0000469 HOST, PORT = "localhost", 9999
Georg Brandl67d69332008-05-18 08:52:59 +0000470 data = " ".join(sys.argv[1:])
471
472 # SOCK_DGRAM is the socket type to use for UDP sockets
473 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
474
475 # As you can see, there is no connect() call; UDP has no connections.
476 # Instead, data is directly sent to the recipient via sendto().
477 sock.sendto(data + "\n", (HOST, PORT))
478 received = sock.recv(1024)
479
480 print "Sent: %s" % data
481 print "Received: %s" % received
482
483The output of the example should look exactly like for the TCP server example.
484
485
486Asynchronous Mixins
487~~~~~~~~~~~~~~~~~~~
488
489To build asynchronous handlers, use the :class:`ThreadingMixIn` and
490:class:`ForkingMixIn` classes.
491
492An example for the :class:`ThreadingMixIn` class::
493
494 import socket
495 import threading
Georg Brandle152a772008-05-24 18:31:28 +0000496 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000497
Georg Brandle152a772008-05-24 18:31:28 +0000498 class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000499
500 def handle(self):
501 data = self.request.recv(1024)
502 cur_thread = threading.currentThread()
503 response = "%s: %s" % (cur_thread.getName(), data)
504 self.request.send(response)
505
Georg Brandle152a772008-05-24 18:31:28 +0000506 class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
Georg Brandl67d69332008-05-18 08:52:59 +0000507 pass
508
509 def client(ip, port, message):
510 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
511 sock.connect((ip, port))
512 sock.send(message)
513 response = sock.recv(1024)
514 print "Received: %s" % response
515 sock.close()
516
517 if __name__ == "__main__":
518 # Port 0 means to select an arbitrary unused port
519 HOST, PORT = "localhost", 0
520
521 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
522 ip, port = server.server_address
523
524 # Start a thread with the server -- that thread will then start one
525 # more thread for each request
526 server_thread = threading.Thread(target=server.serve_forever)
527 # Exit the server thread when the main thread terminates
528 server_thread.setDaemon(True)
529 server_thread.start()
Georg Brandl52f6b6d2009-02-18 00:22:55 +0000530 print "Server loop running in thread:", server_thread.getName()
Georg Brandl67d69332008-05-18 08:52:59 +0000531
532 client(ip, port, "Hello World 1")
533 client(ip, port, "Hello World 2")
534 client(ip, port, "Hello World 3")
535
536 server.shutdown()
537
538The output of the example should look something like this::
539
540 $ python ThreadedTCPServer.py
541 Server loop running in thread: Thread-1
542 Received: Thread-2: Hello World 1
543 Received: Thread-3: Hello World 2
544 Received: Thread-4: Hello World 3
545
546
547The :class:`ForkingMixIn` class is used in the same way, except that the server
548will spawn a new process for each request.