/Doc/library/socketserver.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 547 lines · 378 code · 169 blank · 0 comment · 0 complexity · a16f78ae83385f1ea2eb87e75008a9cb MD5 · raw file

  1. :mod:`SocketServer` --- A framework for network servers
  2. =======================================================
  3. .. module:: SocketServer
  4. :synopsis: A framework for network servers.
  5. .. note::
  6. The :mod:`SocketServer` module has been renamed to :mod:`socketserver` in
  7. Python 3.0. The :term:`2to3` tool will automatically adapt imports when
  8. converting your sources to 3.0.
  9. The :mod:`SocketServer` module simplifies the task of writing network servers.
  10. There are four basic server classes: :class:`TCPServer` uses the Internet TCP
  11. protocol, which provides for continuous streams of data between the client and
  12. server. :class:`UDPServer` uses datagrams, which are discrete packets of
  13. information that may arrive out of order or be lost while in transit. The more
  14. infrequently used :class:`UnixStreamServer` and :class:`UnixDatagramServer`
  15. classes are similar, but use Unix domain sockets; they're not available on
  16. non-Unix platforms. For more details on network programming, consult a book
  17. such as
  18. W. Richard Steven's UNIX Network Programming or Ralph Davis's Win32 Network
  19. Programming.
  20. These four classes process requests :dfn:`synchronously`; each request must be
  21. completed before the next request can be started. This isn't suitable if each
  22. request takes a long time to complete, because it requires a lot of computation,
  23. or because it returns a lot of data which the client is slow to process. The
  24. solution is to create a separate process or thread to handle each request; the
  25. :class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes can be used to
  26. support asynchronous behaviour.
  27. Creating a server requires several steps. First, you must create a request
  28. handler class by subclassing the :class:`BaseRequestHandler` class and
  29. overriding its :meth:`handle` method; this method will process incoming
  30. requests. Second, you must instantiate one of the server classes, passing it
  31. the server's address and the request handler class. Finally, call the
  32. :meth:`handle_request` or :meth:`serve_forever` method of the server object to
  33. process one or many requests.
  34. When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
  35. you should explicitly declare how you want your threads to behave on an abrupt
  36. shutdown. The :class:`ThreadingMixIn` class defines an attribute
  37. *daemon_threads*, which indicates whether or not the server should wait for
  38. thread termination. You should set the flag explicitly if you would like threads
  39. to behave autonomously; the default is :const:`False`, meaning that Python will
  40. not exit until all threads created by :class:`ThreadingMixIn` have exited.
  41. Server classes have the same external methods and attributes, no matter what
  42. network protocol they use.
  43. Server Creation Notes
  44. ---------------------
  45. There are five classes in an inheritance diagram, four of which represent
  46. synchronous servers of four types::
  47. +------------+
  48. | BaseServer |
  49. +------------+
  50. |
  51. v
  52. +-----------+ +------------------+
  53. | TCPServer |------->| UnixStreamServer |
  54. +-----------+ +------------------+
  55. |
  56. v
  57. +-----------+ +--------------------+
  58. | UDPServer |------->| UnixDatagramServer |
  59. +-----------+ +--------------------+
  60. Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
  61. :class:`UnixStreamServer` --- the only difference between an IP and a Unix
  62. stream server is the address family, which is simply repeated in both Unix
  63. server classes.
  64. Forking and threading versions of each type of server can be created using the
  65. :class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes. For instance,
  66. a threading UDP server class is created as follows::
  67. class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  68. The mix-in class must come first, since it overrides a method defined in
  69. :class:`UDPServer`. Setting the various member variables also changes the
  70. behavior of the underlying server mechanism.
  71. To implement a service, you must derive a class from :class:`BaseRequestHandler`
  72. and redefine its :meth:`handle` method. You can then run various versions of
  73. the service by combining one of the server classes with your request handler
  74. class. The request handler class must be different for datagram or stream
  75. services. This can be hidden by using the handler subclasses
  76. :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
  77. Of course, you still have to use your head! For instance, it makes no sense to
  78. use a forking server if the service contains state in memory that can be
  79. modified by different requests, since the modifications in the child process
  80. would never reach the initial state kept in the parent process and passed to
  81. each child. In this case, you can use a threading server, but you will probably
  82. have to use locks to protect the integrity of the shared data.
  83. On the other hand, if you are building an HTTP server where all data is stored
  84. externally (for instance, in the file system), a synchronous class will
  85. essentially render the service "deaf" while one request is being handled --
  86. which may be for a very long time if a client is slow to receive all the data it
  87. has requested. Here a threading or forking server is appropriate.
  88. In some cases, it may be appropriate to process part of a request synchronously,
  89. but to finish processing in a forked child depending on the request data. This
  90. can be implemented by using a synchronous server and doing an explicit fork in
  91. the request handler class :meth:`handle` method.
  92. Another approach to handling multiple simultaneous requests in an environment
  93. that supports neither threads nor :func:`fork` (or where these are too expensive
  94. or inappropriate for the service) is to maintain an explicit table of partially
  95. finished requests and to use :func:`select` to decide which request to work on
  96. next (or whether to handle a new incoming request). This is particularly
  97. important for stream services where each client can potentially be connected for
  98. a long time (if threads or subprocesses cannot be used). See :mod:`asyncore` for
  99. another way to manage this.
  100. .. XXX should data and methods be intermingled, or separate?
  101. how should the distinction between class and instance variables be drawn?
  102. Server Objects
  103. --------------
  104. .. class:: BaseServer
  105. This is the superclass of all Server objects in the module. It defines the
  106. interface, given below, but does not implement most of the methods, which is
  107. done in subclasses.
  108. .. method:: BaseServer.fileno()
  109. Return an integer file descriptor for the socket on which the server is
  110. listening. This function is most commonly passed to :func:`select.select`, to
  111. allow monitoring multiple servers in the same process.
  112. .. method:: BaseServer.handle_request()
  113. Process a single request. This function calls the following methods in
  114. order: :meth:`get_request`, :meth:`verify_request`, and
  115. :meth:`process_request`. If the user-provided :meth:`handle` method of the
  116. handler class raises an exception, the server's :meth:`handle_error` method
  117. will be called. If no request is received within :attr:`self.timeout`
  118. seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
  119. will return.
  120. .. method:: BaseServer.serve_forever(poll_interval=0.5)
  121. Handle requests until an explicit :meth:`shutdown` request. Polls for
  122. shutdown every *poll_interval* seconds.
  123. .. method:: BaseServer.shutdown()
  124. Tells the :meth:`serve_forever` loop to stop and waits until it does.
  125. .. versionadded:: 2.6
  126. .. attribute:: BaseServer.address_family
  127. The family of protocols to which the server's socket belongs.
  128. Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
  129. .. attribute:: BaseServer.RequestHandlerClass
  130. The user-provided request handler class; an instance of this class is created
  131. for each request.
  132. .. attribute:: BaseServer.server_address
  133. The address on which the server is listening. The format of addresses varies
  134. depending on the protocol family; see the documentation for the socket module
  135. for details. For Internet protocols, this is a tuple containing a string giving
  136. the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
  137. .. attribute:: BaseServer.socket
  138. The socket object on which the server will listen for incoming requests.
  139. The server classes support the following class variables:
  140. .. XXX should class variables be covered before instance variables, or vice versa?
  141. .. attribute:: BaseServer.allow_reuse_address
  142. Whether the server will allow the reuse of an address. This defaults to
  143. :const:`False`, and can be set in subclasses to change the policy.
  144. .. attribute:: BaseServer.request_queue_size
  145. The size of the request queue. If it takes a long time to process a single
  146. request, any requests that arrive while the server is busy are placed into a
  147. queue, up to :attr:`request_queue_size` requests. Once the queue is full,
  148. further requests from clients will get a "Connection denied" error. The default
  149. value is usually 5, but this can be overridden by subclasses.
  150. .. attribute:: BaseServer.socket_type
  151. The type of socket used by the server; :const:`socket.SOCK_STREAM` and
  152. :const:`socket.SOCK_DGRAM` are two common values.
  153. .. attribute:: BaseServer.timeout
  154. Timeout duration, measured in seconds, or :const:`None` if no timeout is
  155. desired. If :meth:`handle_request` receives no incoming requests within the
  156. timeout period, the :meth:`handle_timeout` method is called.
  157. There are various server methods that can be overridden by subclasses of base
  158. server classes like :class:`TCPServer`; these methods aren't useful to external
  159. users of the server object.
  160. .. XXX should the default implementations of these be documented, or should
  161. it be assumed that the user will look at SocketServer.py?
  162. .. method:: BaseServer.finish_request()
  163. Actually processes the request by instantiating :attr:`RequestHandlerClass` and
  164. calling its :meth:`handle` method.
  165. .. method:: BaseServer.get_request()
  166. Must accept a request from the socket, and return a 2-tuple containing the *new*
  167. socket object to be used to communicate with the client, and the client's
  168. address.
  169. .. method:: BaseServer.handle_error(request, client_address)
  170. This function is called if the :attr:`RequestHandlerClass`'s :meth:`handle`
  171. method raises an exception. The default action is to print the traceback to
  172. standard output and continue handling further requests.
  173. .. method:: BaseServer.handle_timeout()
  174. This function is called when the :attr:`timeout` attribute has been set to a
  175. value other than :const:`None` and the timeout period has passed with no
  176. requests being received. The default action for forking servers is
  177. to collect the status of any child processes that have exited, while
  178. in threading servers this method does nothing.
  179. .. method:: BaseServer.process_request(request, client_address)
  180. Calls :meth:`finish_request` to create an instance of the
  181. :attr:`RequestHandlerClass`. If desired, this function can create a new process
  182. or thread to handle the request; the :class:`ForkingMixIn` and
  183. :class:`ThreadingMixIn` classes do this.
  184. .. Is there any point in documenting the following two functions?
  185. What would the purpose of overriding them be: initializing server
  186. instance variables, adding new network families?
  187. .. method:: BaseServer.server_activate()
  188. Called by the server's constructor to activate the server. The default behavior
  189. just :meth:`listen`\ s to the server's socket. May be overridden.
  190. .. method:: BaseServer.server_bind()
  191. Called by the server's constructor to bind the socket to the desired address.
  192. May be overridden.
  193. .. method:: BaseServer.verify_request(request, client_address)
  194. Must return a Boolean value; if the value is :const:`True`, the request will be
  195. processed, and if it's :const:`False`, the request will be denied. This function
  196. can be overridden to implement access controls for a server. The default
  197. implementation always returns :const:`True`.
  198. RequestHandler Objects
  199. ----------------------
  200. The request handler class must define a new :meth:`handle` method, and can
  201. override any of the following methods. A new instance is created for each
  202. request.
  203. .. method:: RequestHandler.finish()
  204. Called after the :meth:`handle` method to perform any clean-up actions
  205. required. The default implementation does nothing. If :meth:`setup` or
  206. :meth:`handle` raise an exception, this function will not be called.
  207. .. method:: RequestHandler.handle()
  208. This function must do all the work required to service a request. The
  209. default implementation does nothing. Several instance attributes are
  210. available to it; the request is available as :attr:`self.request`; the client
  211. address as :attr:`self.client_address`; and the server instance as
  212. :attr:`self.server`, in case it needs access to per-server information.
  213. The type of :attr:`self.request` is different for datagram or stream
  214. services. For stream services, :attr:`self.request` is a socket object; for
  215. datagram services, :attr:`self.request` is a pair of string and socket.
  216. However, this can be hidden by using the request handler subclasses
  217. :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which
  218. override the :meth:`setup` and :meth:`finish` methods, and provide
  219. :attr:`self.rfile` and :attr:`self.wfile` attributes. :attr:`self.rfile` and
  220. :attr:`self.wfile` can be read or written, respectively, to get the request
  221. data or return data to the client.
  222. .. method:: RequestHandler.setup()
  223. Called before the :meth:`handle` method to perform any initialization actions
  224. required. The default implementation does nothing.
  225. Examples
  226. --------
  227. :class:`SocketServer.TCPServer` Example
  228. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  229. This is the server side::
  230. import SocketServer
  231. class MyTCPHandler(SocketServer.BaseRequestHandler):
  232. """
  233. The RequestHandler class for our server.
  234. It is instantiated once per connection to the server, and must
  235. override the handle() method to implement communication to the
  236. client.
  237. """
  238. def handle(self):
  239. # self.request is the TCP socket connected to the client
  240. self.data = self.request.recv(1024).strip()
  241. print "%s wrote:" % self.client_address[0]
  242. print self.data
  243. # just send back the same data, but upper-cased
  244. self.request.send(self.data.upper())
  245. if __name__ == "__main__":
  246. HOST, PORT = "localhost", 9999
  247. # Create the server, binding to localhost on port 9999
  248. server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
  249. # Activate the server; this will keep running until you
  250. # interrupt the program with Ctrl-C
  251. server.serve_forever()
  252. An alternative request handler class that makes use of streams (file-like
  253. objects that simplify communication by providing the standard file interface)::
  254. class MyTCPHandler(SocketServer.StreamRequestHandler):
  255. def handle(self):
  256. # self.rfile is a file-like object created by the handler;
  257. # we can now use e.g. readline() instead of raw recv() calls
  258. self.data = self.rfile.readline().strip()
  259. print "%s wrote:" % self.client_address[0]
  260. print self.data
  261. # Likewise, self.wfile is a file-like object used to write back
  262. # to the client
  263. self.wfile.write(self.data.upper())
  264. The difference is that the ``readline()`` call in the second handler will call
  265. ``recv()`` multiple times until it encounters a newline character, while the
  266. single ``recv()`` call in the first handler will just return what has been sent
  267. from the client in one ``send()`` call.
  268. This is the client side::
  269. import socket
  270. import sys
  271. HOST, PORT = "localhost", 9999
  272. data = " ".join(sys.argv[1:])
  273. # Create a socket (SOCK_STREAM means a TCP socket)
  274. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  275. # Connect to server and send data
  276. sock.connect((HOST, PORT))
  277. sock.send(data + "\n")
  278. # Receive data from the server and shut down
  279. received = sock.recv(1024)
  280. sock.close()
  281. print "Sent: %s" % data
  282. print "Received: %s" % received
  283. The output of the example should look something like this:
  284. Server::
  285. $ python TCPServer.py
  286. 127.0.0.1 wrote:
  287. hello world with TCP
  288. 127.0.0.1 wrote:
  289. python is nice
  290. Client::
  291. $ python TCPClient.py hello world with TCP
  292. Sent: hello world with TCP
  293. Received: HELLO WORLD WITH TCP
  294. $ python TCPClient.py python is nice
  295. Sent: python is nice
  296. Received: PYTHON IS NICE
  297. :class:`SocketServer.UDPServer` Example
  298. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  299. This is the server side::
  300. import SocketServer
  301. class MyUDPHandler(SocketServer.BaseRequestHandler):
  302. """
  303. This class works similar to the TCP handler class, except that
  304. self.request consists of a pair of data and client socket, and since
  305. there is no connection the client address must be given explicitly
  306. when sending data back via sendto().
  307. """
  308. def handle(self):
  309. data = self.request[0].strip()
  310. socket = self.request[1]
  311. print "%s wrote:" % self.client_address[0]
  312. print data
  313. socket.sendto(data.upper(), self.client_address)
  314. if __name__ == "__main__":
  315. HOST, PORT = "localhost", 9999
  316. server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
  317. server.serve_forever()
  318. This is the client side::
  319. import socket
  320. import sys
  321. HOST, PORT = "localhost"
  322. data = " ".join(sys.argv[1:])
  323. # SOCK_DGRAM is the socket type to use for UDP sockets
  324. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  325. # As you can see, there is no connect() call; UDP has no connections.
  326. # Instead, data is directly sent to the recipient via sendto().
  327. sock.sendto(data + "\n", (HOST, PORT))
  328. received = sock.recv(1024)
  329. print "Sent: %s" % data
  330. print "Received: %s" % received
  331. The output of the example should look exactly like for the TCP server example.
  332. Asynchronous Mixins
  333. ~~~~~~~~~~~~~~~~~~~
  334. To build asynchronous handlers, use the :class:`ThreadingMixIn` and
  335. :class:`ForkingMixIn` classes.
  336. An example for the :class:`ThreadingMixIn` class::
  337. import socket
  338. import threading
  339. import SocketServer
  340. class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
  341. def handle(self):
  342. data = self.request.recv(1024)
  343. cur_thread = threading.currentThread()
  344. response = "%s: %s" % (cur_thread.getName(), data)
  345. self.request.send(response)
  346. class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
  347. pass
  348. def client(ip, port, message):
  349. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  350. sock.connect((ip, port))
  351. sock.send(message)
  352. response = sock.recv(1024)
  353. print "Received: %s" % response
  354. sock.close()
  355. if __name__ == "__main__":
  356. # Port 0 means to select an arbitrary unused port
  357. HOST, PORT = "localhost", 0
  358. server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
  359. ip, port = server.server_address
  360. # Start a thread with the server -- that thread will then start one
  361. # more thread for each request
  362. server_thread = threading.Thread(target=server.serve_forever)
  363. # Exit the server thread when the main thread terminates
  364. server_thread.setDaemon(True)
  365. server_thread.start()
  366. print "Server loop running in thread:", server_thread.getName()
  367. client(ip, port, "Hello World 1")
  368. client(ip, port, "Hello World 2")
  369. client(ip, port, "Hello World 3")
  370. server.shutdown()
  371. The output of the example should look something like this::
  372. $ python ThreadedTCPServer.py
  373. Server loop running in thread: Thread-1
  374. Received: Thread-2: Hello World 1
  375. Received: Thread-3: Hello World 2
  376. Received: Thread-4: Hello World 3
  377. The :class:`ForkingMixIn` class is used in the same way, except that the server
  378. will spawn a new process for each request.