Skip to content

Instantly share code, notes, and snippets.

@bduggan
Created April 17, 2016 15:18
Show Gist options
  • Save bduggan/970e36413bc6e3b9c7fe41c3d40bd761 to your computer and use it in GitHub Desktop.
Save bduggan/970e36413bc6e3b9c7fe41c3d40bd761 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl6
use v6;
# a webserver that is threaded with a 1 second timeout for clients
# but which does not impose a timeout on the (server) portion that
# is generating the response.
my $host = 'localhost';
my $port = 3333;
my $timeout = 1;
my $response = q:to/HERE/.encode("UTF-8");
HTTP/1.1 200 OK
Content-Length: 6
Connection: close
Content-Type:text/plain
Hello, world
HERE
my $loop =
start {
react {
whenever IO::Socket::Async.listen($host, $port) -> $conn {
my $closed = False;
my $responding = False;
Promise.in($timeout).then({ $conn.close unless $closed || $responding} );
my $req;
whenever $conn.Supply(:bin) -> $buf {
$req ~= $buf.decode('ASCII');
if ($req.contains("\r\n\r\n")) {
$responding = True;
start {
sleep 3; # fake taking a long time to process
$conn.write($response);
$conn.close;
$closed = True;
}
}
}
}
}
}
say "listening on $host:$port";
await $loop;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment