Lesson 12: Connection reuse

Contents
  • Reading assignment
  • Testing for reuse
  • Reuse
  • Aside: stateful protocols
  • Removing the lazy I/O

At the end of the last lesson, we wrote a server function with this type signature:

ioServer :: (Request -> IO Response) -> IO ()

Each time a client connects, ioServer f does the following:

  1. Wait for a client to connect.
  2. Read the request from the socket.
  3. Apply the function f to it to determine the response.
  4. Send the response to the client.
  5. Close the socket.

Often a client will make a series of multiple HTTP requests at once; for example, loading a webpage usually involves an initial request for the HTML, followed by a separate request for each image, stylesheet, etc. Opening and closing sockets times some amount of time, and so HTTP allows us to reuse the socket for multiple requests. The new process will like this:

  1. Wait for a client to connect.
  2. Repeat until the client closes the socket:
    • Read the request from the socket.
    • Apply the function f to it to determine the response.
    • Send the response to the client.
  3. Close the socket.

In this lesson we’re going to write three more iterations of ioServer, First we’ll add support for connection reuse. Then we’ll rewrite it to read the input from the socket as a series of strict BS.ByteStrings instead of representing the entire stream as a single LBS.ByteString.

Sign up for access to the full page, plus the complete archive and all the latest content.