blob: bb933a65b4a2690bc2885caac872290b7519c3fd [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
Robert Collins2f2c8292015-07-29 12:48:42 +120042the server's address and the request handler class. Then call the
Georg Brandl8ec7f652007-08-15 14:28:01 +000043:meth:`handle_request` or :meth:`serve_forever` method of the server object to
Robert Collins2f2c8292015-07-29 12:48:42 +120044process one or many requests. Finally, call :meth:`~BaseServer.server_close`
45to close the socket.
Georg Brandl8ec7f652007-08-15 14:28:01 +000046
47When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
48you should explicitly declare how you want your threads to behave on an abrupt
49shutdown. The :class:`ThreadingMixIn` class defines an attribute
50*daemon_threads*, which indicates whether or not the server should wait for
51thread termination. You should set the flag explicitly if you would like threads
52to behave autonomously; the default is :const:`False`, meaning that Python will
53not exit until all threads created by :class:`ThreadingMixIn` have exited.
54
55Server classes have the same external methods and attributes, no matter what
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +000056network protocol they use.
Georg Brandl8ec7f652007-08-15 14:28:01 +000057
58
59Server Creation Notes
60---------------------
61
62There are five classes in an inheritance diagram, four of which represent
63synchronous servers of four types::
64
65 +------------+
66 | BaseServer |
67 +------------+
68 |
69 v
70 +-----------+ +------------------+
71 | TCPServer |------->| UnixStreamServer |
72 +-----------+ +------------------+
73 |
74 v
75 +-----------+ +--------------------+
76 | UDPServer |------->| UnixDatagramServer |
77 +-----------+ +--------------------+
78
79Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
80:class:`UnixStreamServer` --- the only difference between an IP and a Unix
81stream server is the address family, which is simply repeated in both Unix
82server classes.
83
84Forking and threading versions of each type of server can be created using the
85:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes. For instance,
86a threading UDP server class is created as follows::
87
88 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
89
90The mix-in class must come first, since it overrides a method defined in
Senthil Kumaran6f18b982011-07-04 12:50:02 -070091:class:`UDPServer`. Setting the various attributes also change the
Georg Brandl8ec7f652007-08-15 14:28:01 +000092behavior of the underlying server mechanism.
93
94To implement a service, you must derive a class from :class:`BaseRequestHandler`
95and redefine its :meth:`handle` method. You can then run various versions of
96the service by combining one of the server classes with your request handler
97class. The request handler class must be different for datagram or stream
98services. This can be hidden by using the handler subclasses
99:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
100
101Of course, you still have to use your head! For instance, it makes no sense to
102use a forking server if the service contains state in memory that can be
103modified by different requests, since the modifications in the child process
104would never reach the initial state kept in the parent process and passed to
105each child. In this case, you can use a threading server, but you will probably
106have to use locks to protect the integrity of the shared data.
107
108On the other hand, if you are building an HTTP server where all data is stored
109externally (for instance, in the file system), a synchronous class will
110essentially render the service "deaf" while one request is being handled --
111which may be for a very long time if a client is slow to receive all the data it
112has requested. Here a threading or forking server is appropriate.
113
114In some cases, it may be appropriate to process part of a request synchronously,
115but to finish processing in a forked child depending on the request data. This
116can be implemented by using a synchronous server and doing an explicit fork in
117the request handler class :meth:`handle` method.
118
119Another approach to handling multiple simultaneous requests in an environment
Serhiy Storchakab33336f2013-10-13 23:09:00 +0300120that supports neither threads nor :func:`~os.fork` (or where these are too
121expensive or inappropriate for the service) is to maintain an explicit table of
122partially finished requests and to use :func:`~select.select` to decide which
123request to work on next (or whether to handle a new incoming request). This is
124particularly important for stream services where each client can potentially be
125connected for a long time (if threads or subprocesses cannot be used). See
126:mod:`asyncore` for another way to manage this.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
Georg Brandlb19be572007-12-29 10:57:00 +0000128.. XXX should data and methods be intermingled, or separate?
129 how should the distinction between class and instance variables be drawn?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130
131
132Server Objects
133--------------
134
Georg Brandl9af0c562009-04-05 10:24:20 +0000135.. class:: BaseServer
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136
Georg Brandl9af0c562009-04-05 10:24:20 +0000137 This is the superclass of all Server objects in the module. It defines the
138 interface, given below, but does not implement most of the methods, which is
139 done in subclasses.
140
141
142.. method:: BaseServer.fileno()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143
144 Return an integer file descriptor for the socket on which the server is
145 listening. This function is most commonly passed to :func:`select.select`, to
146 allow monitoring multiple servers in the same process.
147
148
Georg Brandl9af0c562009-04-05 10:24:20 +0000149.. method:: BaseServer.handle_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000151 Process a single request. This function calls the following methods in
152 order: :meth:`get_request`, :meth:`verify_request`, and
153 :meth:`process_request`. If the user-provided :meth:`handle` method of the
154 handler class raises an exception, the server's :meth:`handle_error` method
155 will be called. If no request is received within :attr:`self.timeout`
156 seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
157 will return.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000158
159
Georg Brandl9af0c562009-04-05 10:24:20 +0000160.. method:: BaseServer.serve_forever(poll_interval=0.5)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
Sandro Tosi499718d2012-01-03 22:35:41 +0100162 Handle requests until an explicit :meth:`shutdown` request.
163 Poll for shutdown every *poll_interval* seconds. Ignores :attr:`self.timeout`.
164 If you need to do periodic tasks, do them in another thread.
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000165
166
Georg Brandl9af0c562009-04-05 10:24:20 +0000167.. method:: BaseServer.shutdown()
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000168
Sandro Tosi499718d2012-01-03 22:35:41 +0100169 Tell the :meth:`serve_forever` loop to stop and wait until it does.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000170
Georg Brandl910df2f2008-06-26 18:55:37 +0000171 .. versionadded:: 2.6
172
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173
Robert Collins2f2c8292015-07-29 12:48:42 +1200174.. method:: BaseServer.server_close()
175
176 Clean up the server. May be overridden.
177
178 .. versionadded:: 2.6
179
180
Georg Brandl9af0c562009-04-05 10:24:20 +0000181.. attribute:: BaseServer.address_family
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183 The family of protocols to which the server's socket belongs.
Georg Brandl0aaf5592008-05-11 10:59:39 +0000184 Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185
186
Georg Brandl9af0c562009-04-05 10:24:20 +0000187.. attribute:: BaseServer.RequestHandlerClass
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188
189 The user-provided request handler class; an instance of this class is created
190 for each request.
191
192
Georg Brandl9af0c562009-04-05 10:24:20 +0000193.. attribute:: BaseServer.server_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
195 The address on which the server is listening. The format of addresses varies
196 depending on the protocol family; see the documentation for the socket module
197 for details. For Internet protocols, this is a tuple containing a string giving
198 the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
199
200
Georg Brandl9af0c562009-04-05 10:24:20 +0000201.. attribute:: BaseServer.socket
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
203 The socket object on which the server will listen for incoming requests.
204
Georg Brandl9af0c562009-04-05 10:24:20 +0000205
Georg Brandl8ec7f652007-08-15 14:28:01 +0000206The server classes support the following class variables:
207
Georg Brandlb19be572007-12-29 10:57:00 +0000208.. XXX should class variables be covered before instance variables, or vice versa?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000209
Georg Brandl9af0c562009-04-05 10:24:20 +0000210.. attribute:: BaseServer.allow_reuse_address
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
212 Whether the server will allow the reuse of an address. This defaults to
213 :const:`False`, and can be set in subclasses to change the policy.
214
215
Georg Brandl9af0c562009-04-05 10:24:20 +0000216.. attribute:: BaseServer.request_queue_size
Georg Brandl8ec7f652007-08-15 14:28:01 +0000217
218 The size of the request queue. If it takes a long time to process a single
219 request, any requests that arrive while the server is busy are placed into a
220 queue, up to :attr:`request_queue_size` requests. Once the queue is full,
221 further requests from clients will get a "Connection denied" error. The default
222 value is usually 5, but this can be overridden by subclasses.
223
224
Georg Brandl9af0c562009-04-05 10:24:20 +0000225.. attribute:: BaseServer.socket_type
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226
227 The type of socket used by the server; :const:`socket.SOCK_STREAM` and
Georg Brandl0aaf5592008-05-11 10:59:39 +0000228 :const:`socket.SOCK_DGRAM` are two common values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000229
Georg Brandl9af0c562009-04-05 10:24:20 +0000230
231.. attribute:: BaseServer.timeout
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000232
Jeffrey Yasskine75f59a2008-03-07 06:22:15 +0000233 Timeout duration, measured in seconds, or :const:`None` if no timeout is
234 desired. If :meth:`handle_request` receives no incoming requests within the
235 timeout period, the :meth:`handle_timeout` method is called.
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000236
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200237
Georg Brandl8ec7f652007-08-15 14:28:01 +0000238There are various server methods that can be overridden by subclasses of base
239server classes like :class:`TCPServer`; these methods aren't useful to external
240users of the server object.
241
Georg Brandlb19be572007-12-29 10:57:00 +0000242.. XXX should the default implementations of these be documented, or should
Georg Brandle152a772008-05-24 18:31:28 +0000243 it be assumed that the user will look at SocketServer.py?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
Georg Brandl9af0c562009-04-05 10:24:20 +0000245.. method:: BaseServer.finish_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246
247 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
248 calling its :meth:`handle` method.
249
250
Georg Brandl9af0c562009-04-05 10:24:20 +0000251.. method:: BaseServer.get_request()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252
253 Must accept a request from the socket, and return a 2-tuple containing the *new*
254 socket object to be used to communicate with the client, and the client's
255 address.
256
257
Georg Brandl9af0c562009-04-05 10:24:20 +0000258.. method:: BaseServer.handle_error(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
260 This function is called if the :attr:`RequestHandlerClass`'s :meth:`handle`
261 method raises an exception. The default action is to print the traceback to
262 standard output and continue handling further requests.
263
Georg Brandl9af0c562009-04-05 10:24:20 +0000264
265.. method:: BaseServer.handle_timeout()
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000266
Georg Brandl67d69332008-05-18 08:52:59 +0000267 This function is called when the :attr:`timeout` attribute has been set to a
268 value other than :const:`None` and the timeout period has passed with no
Andrew M. Kuchlinge45a77a2008-01-19 16:26:13 +0000269 requests being received. The default action for forking servers is
270 to collect the status of any child processes that have exited, while
271 in threading servers this method does nothing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000272
Georg Brandl9af0c562009-04-05 10:24:20 +0000273
274.. method:: BaseServer.process_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275
276 Calls :meth:`finish_request` to create an instance of the
277 :attr:`RequestHandlerClass`. If desired, this function can create a new process
278 or thread to handle the request; the :class:`ForkingMixIn` and
279 :class:`ThreadingMixIn` classes do this.
280
Georg Brandl9af0c562009-04-05 10:24:20 +0000281
Georg Brandlb19be572007-12-29 10:57:00 +0000282.. Is there any point in documenting the following two functions?
283 What would the purpose of overriding them be: initializing server
284 instance variables, adding new network families?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285
Georg Brandl9af0c562009-04-05 10:24:20 +0000286.. method:: BaseServer.server_activate()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287
288 Called by the server's constructor to activate the server. The default behavior
289 just :meth:`listen`\ s to the server's socket. May be overridden.
290
291
Georg Brandl9af0c562009-04-05 10:24:20 +0000292.. method:: BaseServer.server_bind()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000293
294 Called by the server's constructor to bind the socket to the desired address.
295 May be overridden.
296
297
Georg Brandl9af0c562009-04-05 10:24:20 +0000298.. method:: BaseServer.verify_request(request, client_address)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000299
300 Must return a Boolean value; if the value is :const:`True`, the request will be
301 processed, and if it's :const:`False`, the request will be denied. This function
302 can be overridden to implement access controls for a server. The default
303 implementation always returns :const:`True`.
304
305
306RequestHandler Objects
307----------------------
308
309The request handler class must define a new :meth:`handle` method, and can
310override any of the following methods. A new instance is created for each
311request.
312
313
Georg Brandl9af0c562009-04-05 10:24:20 +0000314.. method:: RequestHandler.finish()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000315
Georg Brandl67d69332008-05-18 08:52:59 +0000316 Called after the :meth:`handle` method to perform any clean-up actions
Kristján Valur Jónssonb0d1c372012-12-25 22:46:32 +0000317 required. The default implementation does nothing. If :meth:`setup`
318 raises an exception, this function will not be called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319
320
Georg Brandl9af0c562009-04-05 10:24:20 +0000321.. method:: RequestHandler.handle()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000322
Georg Brandl67d69332008-05-18 08:52:59 +0000323 This function must do all the work required to service a request. The
324 default implementation does nothing. Several instance attributes are
325 available to it; the request is available as :attr:`self.request`; the client
326 address as :attr:`self.client_address`; and the server instance as
327 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000328
Georg Brandl67d69332008-05-18 08:52:59 +0000329 The type of :attr:`self.request` is different for datagram or stream
330 services. For stream services, :attr:`self.request` is a socket object; for
331 datagram services, :attr:`self.request` is a pair of string and socket.
332 However, this can be hidden by using the request handler subclasses
333 :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which
334 override the :meth:`setup` and :meth:`finish` methods, and provide
335 :attr:`self.rfile` and :attr:`self.wfile` attributes. :attr:`self.rfile` and
336 :attr:`self.wfile` can be read or written, respectively, to get the request
337 data or return data to the client.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000338
339
Georg Brandl9af0c562009-04-05 10:24:20 +0000340.. method:: RequestHandler.setup()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341
342 Called before the :meth:`handle` method to perform any initialization actions
343 required. The default implementation does nothing.
344
Georg Brandl67d69332008-05-18 08:52:59 +0000345
346Examples
347--------
348
Georg Brandle152a772008-05-24 18:31:28 +0000349:class:`SocketServer.TCPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000350~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
351
352This is the server side::
353
Georg Brandle152a772008-05-24 18:31:28 +0000354 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000355
Georg Brandle152a772008-05-24 18:31:28 +0000356 class MyTCPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000357 """
358 The RequestHandler class for our server.
359
360 It is instantiated once per connection to the server, and must
361 override the handle() method to implement communication to the
362 client.
363 """
364
365 def handle(self):
366 # self.request is the TCP socket connected to the client
367 self.data = self.request.recv(1024).strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200368 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000369 print self.data
370 # just send back the same data, but upper-cased
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800371 self.request.sendall(self.data.upper())
Georg Brandl67d69332008-05-18 08:52:59 +0000372
373 if __name__ == "__main__":
374 HOST, PORT = "localhost", 9999
375
376 # Create the server, binding to localhost on port 9999
Georg Brandle152a772008-05-24 18:31:28 +0000377 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
Georg Brandl67d69332008-05-18 08:52:59 +0000378
379 # Activate the server; this will keep running until you
380 # interrupt the program with Ctrl-C
381 server.serve_forever()
382
383An alternative request handler class that makes use of streams (file-like
384objects that simplify communication by providing the standard file interface)::
385
Georg Brandle152a772008-05-24 18:31:28 +0000386 class MyTCPHandler(SocketServer.StreamRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000387
388 def handle(self):
389 # self.rfile is a file-like object created by the handler;
390 # we can now use e.g. readline() instead of raw recv() calls
391 self.data = self.rfile.readline().strip()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200392 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000393 print self.data
394 # Likewise, self.wfile is a file-like object used to write back
395 # to the client
396 self.wfile.write(self.data.upper())
397
398The difference is that the ``readline()`` call in the second handler will call
399``recv()`` multiple times until it encounters a newline character, while the
400single ``recv()`` call in the first handler will just return what has been sent
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800401from the client in one ``sendall()`` call.
Georg Brandl67d69332008-05-18 08:52:59 +0000402
403
404This is the client side::
405
406 import socket
407 import sys
408
409 HOST, PORT = "localhost", 9999
410 data = " ".join(sys.argv[1:])
411
412 # Create a socket (SOCK_STREAM means a TCP socket)
413 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
414
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200415 try:
416 # Connect to server and send data
417 sock.connect((HOST, PORT))
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800418 sock.sendall(data + "\n")
Georg Brandl67d69332008-05-18 08:52:59 +0000419
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200420 # Receive data from the server and shut down
421 received = sock.recv(1024)
422 finally:
423 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000424
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200425 print "Sent: {}".format(data)
426 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000427
428
429The output of the example should look something like this:
430
431Server::
432
433 $ python TCPServer.py
434 127.0.0.1 wrote:
435 hello world with TCP
436 127.0.0.1 wrote:
437 python is nice
438
439Client::
440
441 $ python TCPClient.py hello world with TCP
442 Sent: hello world with TCP
443 Received: HELLO WORLD WITH TCP
444 $ python TCPClient.py python is nice
445 Sent: python is nice
446 Received: PYTHON IS NICE
447
448
Georg Brandle152a772008-05-24 18:31:28 +0000449:class:`SocketServer.UDPServer` Example
Georg Brandl67d69332008-05-18 08:52:59 +0000450~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
451
452This is the server side::
453
Georg Brandle152a772008-05-24 18:31:28 +0000454 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000455
Georg Brandle152a772008-05-24 18:31:28 +0000456 class MyUDPHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000457 """
458 This class works similar to the TCP handler class, except that
459 self.request consists of a pair of data and client socket, and since
460 there is no connection the client address must be given explicitly
461 when sending data back via sendto().
462 """
463
464 def handle(self):
465 data = self.request[0].strip()
466 socket = self.request[1]
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200467 print "{} wrote:".format(self.client_address[0])
Georg Brandl67d69332008-05-18 08:52:59 +0000468 print data
469 socket.sendto(data.upper(), self.client_address)
470
471 if __name__ == "__main__":
R. David Murray48239612009-11-20 13:29:43 +0000472 HOST, PORT = "localhost", 9999
473 server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
474 server.serve_forever()
Georg Brandl67d69332008-05-18 08:52:59 +0000475
476This is the client side::
477
478 import socket
479 import sys
480
Georg Brandle8ddbec2009-08-24 17:22:05 +0000481 HOST, PORT = "localhost", 9999
Georg Brandl67d69332008-05-18 08:52:59 +0000482 data = " ".join(sys.argv[1:])
483
484 # SOCK_DGRAM is the socket type to use for UDP sockets
485 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
486
487 # As you can see, there is no connect() call; UDP has no connections.
488 # Instead, data is directly sent to the recipient via sendto().
489 sock.sendto(data + "\n", (HOST, PORT))
490 received = sock.recv(1024)
491
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200492 print "Sent: {}".format(data)
493 print "Received: {}".format(received)
Georg Brandl67d69332008-05-18 08:52:59 +0000494
495The output of the example should look exactly like for the TCP server example.
496
497
498Asynchronous Mixins
499~~~~~~~~~~~~~~~~~~~
500
501To build asynchronous handlers, use the :class:`ThreadingMixIn` and
502:class:`ForkingMixIn` classes.
503
504An example for the :class:`ThreadingMixIn` class::
505
506 import socket
507 import threading
Georg Brandle152a772008-05-24 18:31:28 +0000508 import SocketServer
Georg Brandl67d69332008-05-18 08:52:59 +0000509
Georg Brandle152a772008-05-24 18:31:28 +0000510 class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
Georg Brandl67d69332008-05-18 08:52:59 +0000511
512 def handle(self):
513 data = self.request.recv(1024)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200514 cur_thread = threading.current_thread()
515 response = "{}: {}".format(cur_thread.name, data)
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800516 self.request.sendall(response)
Georg Brandl67d69332008-05-18 08:52:59 +0000517
Georg Brandle152a772008-05-24 18:31:28 +0000518 class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
Georg Brandl67d69332008-05-18 08:52:59 +0000519 pass
520
521 def client(ip, port, message):
522 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
523 sock.connect((ip, port))
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200524 try:
Senthil Kumaran607e31e2012-02-09 17:43:31 +0800525 sock.sendall(message)
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200526 response = sock.recv(1024)
527 print "Received: {}".format(response)
528 finally:
529 sock.close()
Georg Brandl67d69332008-05-18 08:52:59 +0000530
531 if __name__ == "__main__":
532 # Port 0 means to select an arbitrary unused port
533 HOST, PORT = "localhost", 0
534
535 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
536 ip, port = server.server_address
537
538 # Start a thread with the server -- that thread will then start one
539 # more thread for each request
540 server_thread = threading.Thread(target=server.serve_forever)
541 # Exit the server thread when the main thread terminates
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200542 server_thread.daemon = True
Georg Brandl67d69332008-05-18 08:52:59 +0000543 server_thread.start()
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200544 print "Server loop running in thread:", server_thread.name
Georg Brandl67d69332008-05-18 08:52:59 +0000545
546 client(ip, port, "Hello World 1")
547 client(ip, port, "Hello World 2")
548 client(ip, port, "Hello World 3")
549
550 server.shutdown()
Robert Collins2f2c8292015-07-29 12:48:42 +1200551 server.server_close()
Georg Brandl67d69332008-05-18 08:52:59 +0000552
Florent Xiclunadf10d7c2011-10-23 23:07:22 +0200553
Georg Brandl67d69332008-05-18 08:52:59 +0000554The output of the example should look something like this::
555
556 $ python ThreadedTCPServer.py
557 Server loop running in thread: Thread-1
558 Received: Thread-2: Hello World 1
559 Received: Thread-3: Hello World 2
560 Received: Thread-4: Hello World 3
561
562
563The :class:`ForkingMixIn` class is used in the same way, except that the server
564will spawn a new process for each request.