blob: faa3d89b98ee3f5dbb24f533fb96516798d1d59f [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
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200228
Georg Brandl8ec7f652007-08-15 14:28:01 +0000229There are various server methods that can be overridden by subclasses of base
230server classes like :class:`TCPServer`; these methods aren't useful to external
231users of the server object.
232
Georg Brandlb19be572007-12-29 10:57:00 +0000233.. XXX should the default implementations of these be documented, or should
Georg Brandle152a772008-05-24 18:31:28 +0000234 it be assumed that the user will look at SocketServer.py?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000235
Georg Brandl9af0c562009-04-05 10:24:20 +0000236.. method:: BaseServer.finish_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237
238 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
239 calling its :meth:`handle` method.
240
241
Georg Brandl9af0c562009-04-05 10:24:20 +0000242.. method:: BaseServer.get_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000243
244 Must accept a request from the socket, and return a 2-tuple containing the *new*
245 socket object to be used to communicate with the client, and the client's
246 address.
247
248
Georg Brandl9af0c562009-04-05 10:24:20 +0000249.. method:: BaseServer.handle_error(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000250
251 This function is called if the :attr:`RequestHandlerClass`'s :meth:`handle`
252 method raises an exception. The default action is to print the traceback to
253 standard output and continue handling further requests.
254
Georg Brandl9af0c562009-04-05 10:24:20 +0000255
256.. method:: BaseServer.handle_timeout()
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000257
Georg Brandl67d69332008-05-18 08:52:59 +0000258 This function is called when the :attr:`timeout` attribute has been set to a
259 value other than :const:`None` and the timeout period has passed with no
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000260 requests being received. The default action for forking servers is
261 to collect the status of any child processes that have exited, while
262 in threading servers this method does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000263
Georg Brandl9af0c562009-04-05 10:24:20 +0000264
265.. method:: BaseServer.process_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266
267 Calls :meth:`finish_request` to create an instance of the
268 :attr:`RequestHandlerClass`. If desired, this function can create a new process
269 or thread to handle the request; the :class:`ForkingMixIn` and
270 :class:`ThreadingMixIn` classes do this.
271
Georg Brandl9af0c562009-04-05 10:24:20 +0000272
Georg Brandlb19be572007-12-29 10:57:00 +0000273.. Is there any point in documenting the following two functions?
274 What would the purpose of overriding them be: initializing server
275 instance variables, adding new network families?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276
Georg Brandl9af0c562009-04-05 10:24:20 +0000277.. method:: BaseServer.server_activate()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000278
279 Called by the server's constructor to activate the server. The default behavior
280 just :meth:`listen`\ s to the server's socket. May be overridden.
281
282
Georg Brandl9af0c562009-04-05 10:24:20 +0000283.. method:: BaseServer.server_bind()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
285 Called by the server's constructor to bind the socket to the desired address.
286 May be overridden.
287
288
Georg Brandl9af0c562009-04-05 10:24:20 +0000289.. method:: BaseServer.verify_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290
291 Must return a Boolean value; if the value is :const:`True`, the request will be
292 processed, and if it's :const:`False`, the request will be denied. This function
293 can be overridden to implement access controls for a server. The default
294 implementation always returns :const:`True`.
295
296
297RequestHandler Objects
298----------------------
299
300The request handler class must define a new :meth:`handle` method, and can
301override any of the following methods. A new instance is created for each
302request.
303
304
Georg Brandl9af0c562009-04-05 10:24:20 +0000305.. method:: RequestHandler.finish()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306
Georg Brandl67d69332008-05-18 08:52:59 +0000307 Called after the :meth:`handle` method to perform any clean-up actions
308 required. The default implementation does nothing. If :meth:`setup` or
309 :meth:`handle` raise an exception, this function will not be called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310
311
Georg Brandl9af0c562009-04-05 10:24:20 +0000312.. method:: RequestHandler.handle()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000313
Georg Brandl67d69332008-05-18 08:52:59 +0000314 This function must do all the work required to service a request. The
315 default implementation does nothing. Several instance attributes are
316 available to it; the request is available as :attr:`self.request`; the client
317 address as :attr:`self.client_address`; and the server instance as
318 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319
Georg Brandl67d69332008-05-18 08:52:59 +0000320 The type of :attr:`self.request` is different for datagram or stream
321 services. For stream services, :attr:`self.request` is a socket object; for
322 datagram services, :attr:`self.request` is a pair of string and socket.
323 However, this can be hidden by using the request handler subclasses
324 :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which
325 override the :meth:`setup` and :meth:`finish` methods, and provide
326 :attr:`self.rfile` and :attr:`self.wfile` attributes. :attr:`self.rfile` and
327 :attr:`self.wfile` can be read or written, respectively, to get the request
328 data or return data to the client.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000329
330
Georg Brandl9af0c562009-04-05 10:24:20 +0000331.. method:: RequestHandler.setup()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
333 Called before the :meth:`handle` method to perform any initialization actions
334 required. The default implementation does nothing.
335
Georg Brandl67d69332008-05-18 08:52:59 +0000336
337Examples
338--------
339
Georg Brandle152a772008-05-24 18:31:28 +0000340:class:`SocketServer.TCPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000341~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
342
343This is the server side::
344
Georg Brandle152a772008-05-24 18:31:28 +0000345 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000346
Georg Brandle152a772008-05-24 18:31:28 +0000347 class MyTCPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000348 """
349 The RequestHandler class for our server.
350
351 It is instantiated once per connection to the server, and must
352 override the handle() method to implement communication to the
353 client.
354 """
355
356 def handle(self):
357 # self.request is the TCP socket connected to the client
358 self.data = self.request.recv(1024).strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200359 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000360 print self.data
361 # just send back the same data, but upper-cased
362 self.request.send(self.data.upper())
363
364 if __name__ == "__main__":
365 HOST, PORT = "localhost", 9999
366
367 # Create the server, binding to localhost on port 9999
Georg Brandle152a772008-05-24 18:31:28 +0000368 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
Georg Brandl67d69332008-05-18 08:52:59 +0000369
370 # Activate the server; this will keep running until you
371 # interrupt the program with Ctrl-C
372 server.serve_forever()
373
374An alternative request handler class that makes use of streams (file-like
375objects that simplify communication by providing the standard file interface)::
376
Georg Brandle152a772008-05-24 18:31:28 +0000377 class MyTCPHandler(SocketServer.StreamRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000378
379 def handle(self):
380 # self.rfile is a file-like object created by the handler;
381 # we can now use e.g. readline() instead of raw recv() calls
382 self.data = self.rfile.readline().strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200383 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000384 print self.data
385 # Likewise, self.wfile is a file-like object used to write back
386 # to the client
387 self.wfile.write(self.data.upper())
388
389The difference is that the ``readline()`` call in the second handler will call
390``recv()`` multiple times until it encounters a newline character, while the
391single ``recv()`` call in the first handler will just return what has been sent
392from the client in one ``send()`` call.
393
394
395This is the client side::
396
397 import socket
398 import sys
399
400 HOST, PORT = "localhost", 9999
401 data = " ".join(sys.argv[1:])
402
403 # Create a socket (SOCK_STREAM means a TCP socket)
404 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
405
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200406 try:
407 # Connect to server and send data
408 sock.connect((HOST, PORT))
409 sock.send(data + "\n")
Georg Brandl67d69332008-05-18 08:52:59 +0000410
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200411 # Receive data from the server and shut down
412 received = sock.recv(1024)
413 finally:
414 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000415
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200416 print "Sent: {}".format(data)
417 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000418
419
420The output of the example should look something like this:
421
422Server::
423
424 $ python TCPServer.py
425 127.0.0.1 wrote:
426 hello world with TCP
427 127.0.0.1 wrote:
428 python is nice
429
430Client::
431
432 $ python TCPClient.py hello world with TCP
433 Sent: hello world with TCP
434 Received: HELLO WORLD WITH TCP
435 $ python TCPClient.py python is nice
436 Sent: python is nice
437 Received: PYTHON IS NICE
438
439
Georg Brandle152a772008-05-24 18:31:28 +0000440:class:`SocketServer.UDPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000441~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
442
443This is the server side::
444
Georg Brandle152a772008-05-24 18:31:28 +0000445 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000446
Georg Brandle152a772008-05-24 18:31:28 +0000447 class MyUDPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000448 """
449 This class works similar to the TCP handler class, except that
450 self.request consists of a pair of data and client socket, and since
451 there is no connection the client address must be given explicitly
452 when sending data back via sendto().
453 """
454
455 def handle(self):
456 data = self.request[0].strip()
457 socket = self.request[1]
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200458 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000459 print data
460 socket.sendto(data.upper(), self.client_address)
461
462 if __name__ == "__main__":
R. David Murray48239612009-11-20 13:29:43 +0000463 HOST, PORT = "localhost", 9999
464 server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
465 server.serve_forever()
Georg Brandl67d69332008-05-18 08:52:59 +0000466
467This is the client side::
468
469 import socket
470 import sys
471
Georg Brandle8ddbec2009-08-24 17:22:05 +0000472 HOST, PORT = "localhost", 9999
Georg Brandl67d69332008-05-18 08:52:59 +0000473 data = " ".join(sys.argv[1:])
474
475 # SOCK_DGRAM is the socket type to use for UDP sockets
476 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
477
478 # As you can see, there is no connect() call; UDP has no connections.
479 # Instead, data is directly sent to the recipient via sendto().
480 sock.sendto(data + "\n", (HOST, PORT))
481 received = sock.recv(1024)
482
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200483 print "Sent: {}".format(data)
484 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000485
486The output of the example should look exactly like for the TCP server example.
487
488
489Asynchronous Mixins
490~~~~~~~~~~~~~~~~~~~
491
492To build asynchronous handlers, use the :class:`ThreadingMixIn` and
493:class:`ForkingMixIn` classes.
494
495An example for the :class:`ThreadingMixIn` class::
496
497 import socket
498 import threading
Georg Brandle152a772008-05-24 18:31:28 +0000499 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000500
Georg Brandle152a772008-05-24 18:31:28 +0000501 class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000502
503 def handle(self):
504 data = self.request.recv(1024)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200505 cur_thread = threading.current_thread()
506 response = "{}: {}".format(cur_thread.name, data)
Georg Brandl67d69332008-05-18 08:52:59 +0000507 self.request.send(response)
508
Georg Brandle152a772008-05-24 18:31:28 +0000509 class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
Georg Brandl67d69332008-05-18 08:52:59 +0000510 pass
511
512 def client(ip, port, message):
513 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
514 sock.connect((ip, port))
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200515 try:
516 sock.send(message)
517 response = sock.recv(1024)
518 print "Received: {}".format(response)
519 finally:
520 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000521
522 if __name__ == "__main__":
523 # Port 0 means to select an arbitrary unused port
524 HOST, PORT = "localhost", 0
525
526 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
527 ip, port = server.server_address
528
529 # Start a thread with the server -- that thread will then start one
530 # more thread for each request
531 server_thread = threading.Thread(target=server.serve_forever)
532 # Exit the server thread when the main thread terminates
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200533 server_thread.daemon = True
Georg Brandl67d69332008-05-18 08:52:59 +0000534 server_thread.start()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200535 print "Server loop running in thread:", server_thread.name
Georg Brandl67d69332008-05-18 08:52:59 +0000536
537 client(ip, port, "Hello World 1")
538 client(ip, port, "Hello World 2")
539 client(ip, port, "Hello World 3")
540
541 server.shutdown()
542
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200543
Georg Brandl67d69332008-05-18 08:52:59 +0000544The output of the example should look something like this::
545
546 $ python ThreadedTCPServer.py
547 Server loop running in thread: Thread-1
548 Received: Thread-2: Hello World 1
549 Received: Thread-3: Hello World 2
550 Received: Thread-4: Hello World 3
551
552
553The :class:`ForkingMixIn` class is used in the same way, except that the server
554will spawn a new process for each request.