# "A peer that stalls, a peer that never stops": a fake HTTP server in a# task on a loopback port. The first request gets no answer at all; the# second gets a Content-Length of 999999999 and a body that keeps coming.import"http.j"as http;
use io;
use net;
use binary;
usetask;
use time;
use encoding;
funcserveStall(conn asnet.Conn) {
net.readBytes($conn, 4096);
time.sleep(time.fromMilliseconds(2000));
net.close($conn);
}
funcserveEndless(conn asnet.Conn) {
net.readBytes($conn, 4096);
try {
net.writeBytes($conn, encoding.encode("utf-8",
"HTTP/1.1 200 OK\r\nContent-Length: 999999999\r\n\r\n"));
def chunk asbytesinitbinary.make(65536);
for (def i in0..15259) {
net.writeBytes($conn, $chunk);
}
} catch (e) {
# the client hung up once it saw the capreturnnull;
}
net.close($conn);
}
def ln asnet.Listener initnet.listen("127.0.0.1:0");
def url asstringinit"http://" + net.address($ln) + "/";
funcfakeServer(ln asnet.Listener) {
def first asnet.Conn initnet.accept($ln);
def stall astaskofnullinitspawn { serveStall($first); };
serveEndless(net.accept($ln));
task.wait($stall);
}
def fake astaskofnullinitspawn { fakeServer($ln); };
# fake server: no answer, then a 999999999-byte bodyfor (def i in0..2) {
try {
http.requestWith("GET", $url, {}, "", 500, 1048576);
} catch (e) {
io.printf("%s | %s\n", $e.kind, $e.message);
}
}
task.wait($fake);