         public func channelReadComplete(ctx: ChannelHandlerContext) {
             ctx.flush().whenComplete {
                 assertSuccess($0)
+                self.maybeClose(ctx: ctx)
+            }
+        }
+
+        // We should only close the connection when the remote peer has sent the entire request
+        // and we have sent our entire response.
+        private func maybeClose(ctx: ChannelHandlerContext) {
+            if sentEnd && seenEnd && !closed {
+                closed = true
+                ctx.close().whenComplete { r in
+                    assertSuccess(r)
+                }
             }
         }
     }

                    }
                    ctx.write(data: self.wrapOutboundOut(.end(nil))).whenComplete { r in
                        assertSuccess(r)
                        ctx.close().whenComplete { r in
                            assertSuccess(r)
                        }
                    }
                case "/204":
                    var head = HTTPResponseHead(version: req.version, status: .noContent)

                    }
                    ctx.write(data: self.wrapOutboundOut(.end(nil))).whenComplete { r in
                        assertSuccess(r)
                        self.sentEnd = true
                        self.maybeClose(ctx: ctx)
                    }
                case "/head":
                    var head = HTTPResponseHead(version: req.version, status: .ok)
