blob: 06ed134b0f39f866b53b96e517cc6f6c81dd59fb [file] [log] [blame]
Guido van Rossume7e578f1995-08-04 04:00:20 +00001"""Generic socket server classes.
2
3This module tries to capture the various aspects of defining a server:
4
Guido van Rossum90cb9062001-01-19 00:44:41 +00005For socket-based servers:
6
Guido van Rossume7e578f1995-08-04 04:00:20 +00007- address family:
Martin v. Löwisa43c2f82001-07-24 20:34:08 +00008 - AF_INET{,6}: IP (Internet Protocol) sockets (default)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00009 - AF_UNIX: Unix domain sockets
10 - others, e.g. AF_DECNET are conceivable (see <socket.h>
Guido van Rossume7e578f1995-08-04 04:00:20 +000011- socket type:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000012 - SOCK_STREAM (reliable stream, e.g. TCP)
13 - SOCK_DGRAM (datagrams, e.g. UDP)
Guido van Rossum90cb9062001-01-19 00:44:41 +000014
15For request-based servers (including socket-based):
16
Guido van Rossume7e578f1995-08-04 04:00:20 +000017- client address verification before further looking at the request
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000018 (This is actually a hook for any processing that needs to look
19 at the request before anything else, e.g. logging)
Guido van Rossume7e578f1995-08-04 04:00:20 +000020- how to handle multiple requests:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000021 - synchronous (one request is handled at a time)
22 - forking (each request is handled by a new process)
23 - threading (each request is handled by a new thread)
Guido van Rossume7e578f1995-08-04 04:00:20 +000024
25The classes in this module favor the server type that is simplest to
26write: a synchronous TCP/IP server. This is bad class design, but
27save some typing. (There's also the issue that a deep class hierarchy
28slows down method lookups.)
29
Guido van Rossum90cb9062001-01-19 00:44:41 +000030There are five classes in an inheritance diagram, four of which represent
Guido van Rossume7e578f1995-08-04 04:00:20 +000031synchronous servers of four types:
32
Guido van Rossum90cb9062001-01-19 00:44:41 +000033 +------------+
34 | BaseServer |
35 +------------+
36 |
37 v
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000038 +-----------+ +------------------+
39 | TCPServer |------->| UnixStreamServer |
40 +-----------+ +------------------+
41 |
42 v
43 +-----------+ +--------------------+
44 | UDPServer |------->| UnixDatagramServer |
45 +-----------+ +--------------------+
Guido van Rossume7e578f1995-08-04 04:00:20 +000046
Guido van Rossumdb2b70c1997-07-16 16:21:38 +000047Note that UnixDatagramServer derives from UDPServer, not from
Guido van Rossume7e578f1995-08-04 04:00:20 +000048UnixStreamServer -- the only difference between an IP and a Unix
49stream server is the address family, which is simply repeated in both
Guido van Rossumdb2b70c1997-07-16 16:21:38 +000050unix server classes.
Guido van Rossume7e578f1995-08-04 04:00:20 +000051
52Forking and threading versions of each type of server can be created
53using the ForkingServer and ThreadingServer mix-in classes. For
54instance, a threading UDP server class is created as follows:
55
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000056 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
Guido van Rossume7e578f1995-08-04 04:00:20 +000057
Guido van Rossumdb2b70c1997-07-16 16:21:38 +000058The Mix-in class must come first, since it overrides a method defined
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +000059in UDPServer! Setting the various member variables also changes
60the behavior of the underlying server mechanism.
Guido van Rossume7e578f1995-08-04 04:00:20 +000061
62To implement a service, you must derive a class from
63BaseRequestHandler and redefine its handle() method. You can then run
64various versions of the service by combining one of the server classes
65with your request handler class.
66
67The request handler class must be different for datagram or stream
68services. This can be hidden by using the mix-in request handler
69classes StreamRequestHandler or DatagramRequestHandler.
70
71Of course, you still have to use your head!
72
73For instance, it makes no sense to use a forking server if the service
74contains state in memory that can be modified by requests (since the
75modifications in the child process would never reach the initial state
76kept in the parent process and passed to each child). In this case,
77you can use a threading server, but you will probably have to use
78locks to avoid two requests that come in nearly simultaneous to apply
79conflicting changes to the server state.
80
81On the other hand, if you are building e.g. an HTTP server, where all
82data is stored externally (e.g. in the file system), a synchronous
83class will essentially render the service "deaf" while one request is
84being handled -- which may be for a very long time if a client is slow
85to reqd all the data it has requested. Here a threading or forking
86server is appropriate.
87
88In some cases, it may be appropriate to process part of a request
89synchronously, but to finish processing in a forked child depending on
90the request data. This can be implemented by using a synchronous
Guido van Rossum90cb9062001-01-19 00:44:41 +000091server and doing an explicit fork in the request handler class
Guido van Rossume7e578f1995-08-04 04:00:20 +000092handle() method.
93
94Another approach to handling multiple simultaneous requests in an
95environment that supports neither threads nor fork (or where these are
96too expensive or inappropriate for the service) is to maintain an
97explicit table of partially finished requests and to use select() to
98decide which request to work on next (or whether to handle a new
99incoming request). This is particularly important for stream services
100where each client can potentially be connected for a long time (if
Guido van Rossum90cb9062001-01-19 00:44:41 +0000101threads or subprocesses cannot be used).
Guido van Rossume7e578f1995-08-04 04:00:20 +0000102
103Future work:
104- Standard classes for Sun RPC (which uses either UDP or TCP)
105- Standard mix-in classes to implement various authentication
106 and encryption schemes
107- Standard framework for select-based multiplexing
108
109XXX Open problems:
110- What to do with out-of-band data?
111
Guido van Rossum90cb9062001-01-19 00:44:41 +0000112BaseServer:
113- split generic "request" functionality out into BaseServer class.
114 Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
115
116 example: read entries from a SQL database (requires overriding
117 get_request() to return a table entry from the database).
118 entry is processed by a RequestHandlerClass.
119
Guido van Rossume7e578f1995-08-04 04:00:20 +0000120"""
121
Guido van Rossum10b04182001-01-19 16:45:46 +0000122# Author of the BaseServer patch: Luke Kenneth Casson Leighton
Guido van Rossume7e578f1995-08-04 04:00:20 +0000123
Guido van Rossum7de4d642001-07-10 11:50:09 +0000124# XXX Warning!
125# There is a test suite for this module, but it cannot be run by the
126# standard regression test.
127# To run it manually, run Lib/test/test_socketserver.py.
128
129__version__ = "0.4"
Guido van Rossume7e578f1995-08-04 04:00:20 +0000130
131
132import socket
133import sys
134import os
135
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000136__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
137 "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
Guido van Rossum7de4d642001-07-10 11:50:09 +0000138 "StreamRequestHandler","DatagramRequestHandler",
139 "ThreadingMixIn", "ForkingMixIn"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000140if hasattr(socket, "AF_UNIX"):
141 __all__.extend(["UnixStreamServer","UnixDatagramServer",
142 "ThreadingUnixStreamServer",
143 "ThreadingUnixDatagramServer"])
Guido van Rossume7e578f1995-08-04 04:00:20 +0000144
Guido van Rossum90cb9062001-01-19 00:44:41 +0000145class BaseServer:
146
147 """Base class for server classes.
148
149 Methods for the caller:
150
151 - __init__(server_address, RequestHandlerClass)
152 - serve_forever()
153 - handle_request() # if you do not use serve_forever()
154 - fileno() -> int # for select()
155
156 Methods that may be overridden:
157
158 - server_bind()
159 - server_activate()
160 - get_request() -> request, client_address
161 - verify_request(request, client_address)
162 - server_close()
163 - process_request(request, client_address)
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000164 - close_request(request)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000165 - handle_error()
166
167 Methods for derived classes:
168
169 - finish_request(request, client_address)
170
171 Class variables that may be overridden by derived classes or
172 instances:
173
174 - address_family
175 - socket_type
Barry Warsawb97f0b72003-10-09 23:48:52 +0000176 - allow_reuse_address
Guido van Rossum90cb9062001-01-19 00:44:41 +0000177
178 Instance variables:
179
180 - RequestHandlerClass
181 - socket
182
183 """
184
185 def __init__(self, server_address, RequestHandlerClass):
186 """Constructor. May be extended, do not override."""
187 self.server_address = server_address
188 self.RequestHandlerClass = RequestHandlerClass
189
190 def server_activate(self):
191 """Called by constructor to activate the server.
192
193 May be overridden.
194
195 """
196 pass
197
198 def serve_forever(self):
199 """Handle one request at a time until doomsday."""
200 while 1:
201 self.handle_request()
202
203 # The distinction between handling, getting, processing and
204 # finishing a request is fairly arbitrary. Remember:
205 #
206 # - handle_request() is the top-level call. It calls
207 # get_request(), verify_request() and process_request()
208 # - get_request() is different for stream or datagram sockets
209 # - process_request() is the place that may fork a new process
210 # or create a new thread to finish the request
211 # - finish_request() instantiates the request handler class;
212 # this constructor will handle the request all by itself
213
214 def handle_request(self):
215 """Handle one request, possibly blocking."""
216 try:
217 request, client_address = self.get_request()
218 except socket.error:
219 return
220 if self.verify_request(request, client_address):
221 try:
222 self.process_request(request, client_address)
223 except:
224 self.handle_error(request, client_address)
Guido van Rossum7de4d642001-07-10 11:50:09 +0000225 self.close_request(request)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000226
227 def verify_request(self, request, client_address):
228 """Verify the request. May be overridden.
229
Tim Petersbc0e9102002-04-04 22:55:58 +0000230 Return True if we should proceed with this request.
Guido van Rossum90cb9062001-01-19 00:44:41 +0000231
232 """
Tim Petersbc0e9102002-04-04 22:55:58 +0000233 return True
Guido van Rossum90cb9062001-01-19 00:44:41 +0000234
235 def process_request(self, request, client_address):
236 """Call finish_request.
237
238 Overridden by ForkingMixIn and ThreadingMixIn.
239
240 """
241 self.finish_request(request, client_address)
Guido van Rossum7de4d642001-07-10 11:50:09 +0000242 self.close_request(request)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000243
244 def server_close(self):
245 """Called to clean-up the server.
246
247 May be overridden.
248
249 """
250 pass
251
252 def finish_request(self, request, client_address):
253 """Finish one request by instantiating RequestHandlerClass."""
254 self.RequestHandlerClass(request, client_address, self)
255
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000256 def close_request(self, request):
257 """Called to clean up an individual request."""
258 pass
259
Guido van Rossum90cb9062001-01-19 00:44:41 +0000260 def handle_error(self, request, client_address):
261 """Handle an error gracefully. May be overridden.
262
263 The default is to print a traceback and continue.
264
265 """
266 print '-'*40
267 print 'Exception happened during processing of request from',
268 print client_address
269 import traceback
270 traceback.print_exc() # XXX But this goes to stderr!
271 print '-'*40
272
273
274class TCPServer(BaseServer):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000275
276 """Base class for various socket-based server classes.
277
278 Defaults to synchronous IP stream (i.e., TCP).
279
280 Methods for the caller:
281
282 - __init__(server_address, RequestHandlerClass)
283 - serve_forever()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000284 - handle_request() # if you don't use serve_forever()
285 - fileno() -> int # for select()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000286
287 Methods that may be overridden:
288
289 - server_bind()
290 - server_activate()
291 - get_request() -> request, client_address
292 - verify_request(request, client_address)
293 - process_request(request, client_address)
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000294 - close_request(request)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000295 - handle_error()
296
297 Methods for derived classes:
298
299 - finish_request(request, client_address)
300
301 Class variables that may be overridden by derived classes or
302 instances:
303
304 - address_family
305 - socket_type
306 - request_queue_size (only for stream sockets)
Barry Warsaw3aaad502003-10-09 22:44:05 +0000307 - allow_reuse_address
Guido van Rossume7e578f1995-08-04 04:00:20 +0000308
309 Instance variables:
310
311 - server_address
312 - RequestHandlerClass
313 - socket
314
315 """
316
317 address_family = socket.AF_INET
318
319 socket_type = socket.SOCK_STREAM
320
321 request_queue_size = 5
322
Raymond Hettingerc8f80342002-08-25 16:36:49 +0000323 allow_reuse_address = False
Guido van Rossume3c7a5f2000-05-09 14:53:29 +0000324
Guido van Rossume7e578f1995-08-04 04:00:20 +0000325 def __init__(self, server_address, RequestHandlerClass):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000326 """Constructor. May be extended, do not override."""
Guido van Rossum90cb9062001-01-19 00:44:41 +0000327 BaseServer.__init__(self, server_address, RequestHandlerClass)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000328 self.socket = socket.socket(self.address_family,
329 self.socket_type)
330 self.server_bind()
331 self.server_activate()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000332
333 def server_bind(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000334 """Called by constructor to bind the socket.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000335
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000336 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000337
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000338 """
Guido van Rossume3c7a5f2000-05-09 14:53:29 +0000339 if self.allow_reuse_address:
340 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000341 self.socket.bind(self.server_address)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000342
343 def server_activate(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000344 """Called by constructor to activate the server.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000345
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000346 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000347
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000348 """
349 self.socket.listen(self.request_queue_size)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000350
Guido van Rossum90cb9062001-01-19 00:44:41 +0000351 def server_close(self):
352 """Called to clean-up the server.
353
354 May be overridden.
355
356 """
357 self.socket.close()
358
Guido van Rossume7e578f1995-08-04 04:00:20 +0000359 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000360 """Return socket file number.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000361
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000362 Interface required by select().
Guido van Rossume7e578f1995-08-04 04:00:20 +0000363
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000364 """
365 return self.socket.fileno()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000366
Guido van Rossume7e578f1995-08-04 04:00:20 +0000367 def get_request(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000368 """Get the request and client address from the socket.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000369
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000370 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000371
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000372 """
373 return self.socket.accept()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000374
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000375 def close_request(self, request):
376 """Called to clean up an individual request."""
377 request.close()
378
Guido van Rossume7e578f1995-08-04 04:00:20 +0000379
380class UDPServer(TCPServer):
381
382 """UDP server class."""
383
Raymond Hettingerc8f80342002-08-25 16:36:49 +0000384 allow_reuse_address = False
Guido van Rossum90cb9062001-01-19 00:44:41 +0000385
Guido van Rossume7e578f1995-08-04 04:00:20 +0000386 socket_type = socket.SOCK_DGRAM
387
388 max_packet_size = 8192
389
390 def get_request(self):
Guido van Rossum32490821998-06-16 02:27:33 +0000391 data, client_addr = self.socket.recvfrom(self.max_packet_size)
392 return (data, self.socket), client_addr
393
394 def server_activate(self):
395 # No need to call listen() for UDP.
396 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000397
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000398 def close_request(self, request):
399 # No need to close anything.
400 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000401
Guido van Rossume7e578f1995-08-04 04:00:20 +0000402class ForkingMixIn:
403
404 """Mix-in class to handle each request in a new process."""
405
406 active_children = None
Guido van Rossum2ab455a1999-07-28 21:39:28 +0000407 max_children = 40
Guido van Rossume7e578f1995-08-04 04:00:20 +0000408
409 def collect_children(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000410 """Internal routine to wait for died children."""
411 while self.active_children:
Guido van Rossum2ab455a1999-07-28 21:39:28 +0000412 if len(self.active_children) < self.max_children:
413 options = os.WNOHANG
414 else:
415 # If the maximum number of children are already
416 # running, block while waiting for a child to exit
417 options = 0
Guido van Rossumbfadac01999-06-17 15:41:33 +0000418 try:
Guido van Rossum2ab455a1999-07-28 21:39:28 +0000419 pid, status = os.waitpid(0, options)
Guido van Rossumbfadac01999-06-17 15:41:33 +0000420 except os.error:
421 pid = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 if not pid: break
423 self.active_children.remove(pid)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000424
425 def process_request(self, request, client_address):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 """Fork a new subprocess to process the request."""
427 self.collect_children()
428 pid = os.fork()
429 if pid:
430 # Parent process
431 if self.active_children is None:
432 self.active_children = []
433 self.active_children.append(pid)
Guido van Rossum7de4d642001-07-10 11:50:09 +0000434 self.close_request(request)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000435 return
436 else:
437 # Child process.
438 # This must never return, hence os._exit()!
439 try:
440 self.finish_request(request, client_address)
441 os._exit(0)
442 except:
443 try:
Guido van Rossum7de4d642001-07-10 11:50:09 +0000444 self.handle_error(request, client_address)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000445 finally:
446 os._exit(1)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000447
448
449class ThreadingMixIn:
Guido van Rossume7e578f1995-08-04 04:00:20 +0000450 """Mix-in class to handle each request in a new thread."""
451
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +0000452 # Decides how threads will act upon termination of the
453 # main process
Fred Drake132e0e82002-11-22 14:22:49 +0000454 daemon_threads = False
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +0000455
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000456 def process_request_thread(self, request, client_address):
Guido van Rossum83c32812001-10-23 21:42:45 +0000457 """Same as in BaseServer but as a thread.
458
459 In addition, exception handling is done here.
460
461 """
462 try:
463 self.finish_request(request, client_address)
464 self.close_request(request)
465 except:
466 self.handle_error(request, client_address)
467 self.close_request(request)
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000468
Guido van Rossume7e578f1995-08-04 04:00:20 +0000469 def process_request(self, request, client_address):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000470 """Start a new thread to process the request."""
Jeremy Hylton75260271999-10-12 16:20:13 +0000471 import threading
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000472 t = threading.Thread(target = self.process_request_thread,
Jeremy Hylton75260271999-10-12 16:20:13 +0000473 args = (request, client_address))
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +0000474 if self.daemon_threads:
475 t.setDaemon (1)
Jeremy Hylton75260271999-10-12 16:20:13 +0000476 t.start()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000477
478
479class ForkingUDPServer(ForkingMixIn, UDPServer): pass
480class ForkingTCPServer(ForkingMixIn, TCPServer): pass
481
482class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
483class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
484
Guido van Rossum67a40e81998-11-30 15:07:01 +0000485if hasattr(socket, 'AF_UNIX'):
486
487 class UnixStreamServer(TCPServer):
488 address_family = socket.AF_UNIX
489
490 class UnixDatagramServer(UDPServer):
491 address_family = socket.AF_UNIX
492
493 class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
494
495 class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000496
497class BaseRequestHandler:
498
499 """Base class for request handler classes.
500
501 This class is instantiated for each request to be handled. The
502 constructor sets the instance variables request, client_address
503 and server, and then calls the handle() method. To implement a
504 specific service, all you need to do is to derive a class which
505 defines a handle() method.
506
507 The handle() method can find the request as self.request, the
Guido van Rossumfdb3d1a1998-11-16 19:06:30 +0000508 client address as self.client_address, and the server (in case it
Guido van Rossume7e578f1995-08-04 04:00:20 +0000509 needs access to per-server information) as self.server. Since a
510 separate instance is created for each request, the handle() method
511 can define arbitrary other instance variariables.
512
513 """
514
515 def __init__(self, request, client_address, server):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000516 self.request = request
517 self.client_address = client_address
518 self.server = server
519 try:
520 self.setup()
521 self.handle()
522 self.finish()
523 finally:
524 sys.exc_traceback = None # Help garbage collection
Guido van Rossume7e578f1995-08-04 04:00:20 +0000525
526 def setup(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000527 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000528
Guido van Rossume7e578f1995-08-04 04:00:20 +0000529 def handle(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000530 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000531
532 def finish(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000533 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000534
535
536# The following two classes make it possible to use the same service
537# class for stream or datagram servers.
538# Each class sets up these instance variables:
539# - rfile: a file object from which receives the request is read
540# - wfile: a file object to which the reply is written
541# When the handle() method returns, wfile is flushed properly
542
543
544class StreamRequestHandler(BaseRequestHandler):
545
546 """Define self.rfile and self.wfile for stream sockets."""
547
Guido van Rossum01fed4d2000-09-01 03:25:14 +0000548 # Default buffer sizes for rfile, wfile.
549 # We default rfile to buffered because otherwise it could be
550 # really slow for large data (a getc() call per byte); we make
551 # wfile unbuffered because (a) often after a write() we want to
552 # read and we need to flush the line; (b) big writes to unbuffered
553 # files are typically optimized by stdio even when big reads
554 # aren't.
555 rbufsize = -1
556 wbufsize = 0
557
Guido van Rossume7e578f1995-08-04 04:00:20 +0000558 def setup(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000559 self.connection = self.request
Guido van Rossum01fed4d2000-09-01 03:25:14 +0000560 self.rfile = self.connection.makefile('rb', self.rbufsize)
561 self.wfile = self.connection.makefile('wb', self.wbufsize)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000562
563 def finish(self):
Anthony Baxter4cedc1e2003-01-02 03:07:48 +0000564 if not self.wfile.closed:
565 self.wfile.flush()
Guido van Rossum1d5102c1998-04-03 16:49:52 +0000566 self.wfile.close()
567 self.rfile.close()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000568
569
570class DatagramRequestHandler(BaseRequestHandler):
571
Guido van Rossum7de4d642001-07-10 11:50:09 +0000572 # XXX Regrettably, I cannot get this working on Linux;
573 # s.recvfrom() doesn't return a meaningful client address.
574
Guido van Rossume7e578f1995-08-04 04:00:20 +0000575 """Define self.rfile and self.wfile for datagram sockets."""
576
577 def setup(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000578 import StringIO
579 self.packet, self.socket = self.request
580 self.rfile = StringIO.StringIO(self.packet)
Guido van Rossumbeae4772002-04-15 00:36:48 +0000581 self.wfile = StringIO.StringIO()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000582
583 def finish(self):
Guido van Rossum32490821998-06-16 02:27:33 +0000584 self.socket.sendto(self.wfile.getvalue(), self.client_address)