                     try! socket.write(from: writeBuffer)
                     httpParser.reset()
                 }
+                logger.debug("Closed connection to \(socket.remoteHostname)")
                 socket.close()
+                self.socket = nil
             }
         }
     }

    import NetService
#endif

fileprivate let logger = getLogger("hap")


public class Server: NSObject, NetServiceDelegate {
    public class Connection: NSObject {
        var context = [String: Any]()
        func listen(socket: Socket, queue: DispatchQueue, application: @escaping Application) {
            let httpParser = HTTPParser(isRequest: true)
            var cryptographer: Cryptographer? = nil
            let request = HTTPServerRequest(socket: socket, httpParser: httpParser)

        queue.async {
            while self.socket.isListening {
                let client = try! self.socket.acceptClientConnection()
                logger.info("Accepted connection from \(client.remoteHostname)")
                DispatchQueue.main.async {
                    _ = Connection().listen(socket: client, queue: self.queue, application: self.application)
                }
