<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
<?php 

include "server.inc";

function respond($client, $msg) {
	$r = new http\Env\Response;
	$r->setEnvRequest($msg)
		->setHeader("X-Req", $msg->getRequestUrl())
		->send($client);
}

serve(function($client) {
	$R = array(STDIN); $W = $E = array();
	if (!stream_select($R, $W, $E, 10, 0)) {
		logger("Client %d timed out", (int) $client);
		return;
	}
	$count = trim(fgets(STDIN));
	logger("Expecting %d messages from client %d", $count, (int) $client);
	/* the peek message */
	respond($client, new http\Message($client, false));
	logger("Handled the peek request of client %d", (int) $client);
	/* pipelined messages */
	$req = array();
	for ($i=0; $i < $count; ++ $i) {
		$req[] = $m = new http\Message($client, false);
		logger("Read request no. %d from client %d (%s)", $i+1, (int) $client, $m->getRequestUrl());
	}
	foreach ($req as $i => $msg) {
		respond($client, $msg);
		logger("Sent response no. %d to client %d", $i+1, (int) $client);
	}
});
