private void serviceConnect(
      String targetId, HttpServletRequest httpRequest, HttpServletResponse httpResponse)
      throws IOException {
    unschedule(targetId);

    ClientDelegate client = gateway.getClientDelegate(targetId);
    if (client == null) {
      // Expired client tries to connect without handshake
      httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return;
    }

    flush(client, httpRequest, httpResponse);

    if (client.isClosed()) gateway.removeClientDelegate(targetId);
  }
  private void flush(
      ClientDelegate client, HttpServletRequest httpRequest, HttpServletResponse httpResponse)
      throws IOException {
    List<RHTTPRequest> requests = client.process(httpRequest);
    if (requests != null) {
      // Schedule before sending the requests, to avoid that the remote client
      // reconnects before we have scheduled the expiration timeout.
      if (!client.isClosed()) schedule(client);

      ServletOutputStream output = httpResponse.getOutputStream();
      for (RHTTPRequest request : requests) output.write(request.getFrameBytes());
      // I could count the framed bytes of all requests and set a Content-Length header,
      // but the implementation of ServletOutputStream takes care of everything:
      // if the request was HTTP/1.1, then flushing result in a chunked response, but the
      // client know how to handle it; if the request was HTTP/1.0, then no chunking.
      // To avoid chunking in HTTP/1.1 I must set the Content-Length header.
      output.flush();
      logger.debug("Delivered to device {} requests {} ", client.getTargetId(), requests);
    }
  }