简单的非阻塞网络服务器
Simple non-blocking web server
我正在尝试使用 Perl6 制作一个简单的非阻塞 Web 服务器,但很可能我不明白这里的某些内容。
示例:
#!/usr/bin/env perl6
use v6;
react {
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn {
whenever $conn.Supply(:bin) -> $buf {
say "-" x 70 ~ "\n" ~ $buf.decode('UTF-8').trim-trailing;
sleep 5; # HERE
my $response = "HTTP/1.0 200 OK\x0D\x0A\x0D\x0A";
$response ~= q:to/END/;
<html>
<head>
<title>Demo page</title>
</head>
<body>
<h1>Title here</h1>
<p>lorem ipsum here</p>
</body>
</html>
END
await $conn.write: $response.encode('utf-8');
$conn.close();
}
}
}
此处的示例与文档中的通用示例几乎相同https://docs.perl6.org/type/IO::Socket::Async
问题:
为什么页面不是并行提供的,而是按顺序提供给所有客户端的?
在这里回答我自己的问题。我是 perl6 的初学者,所以如果我在这里做一些奇怪的事情,请修复我。
使用 promises 似乎可以解决这个问题。我之前假设 IO::Socket::Async 会为我创建承诺,请求将由模块并行处理。
#!/usr/bin/env perl6
use v6;
my @promises;
react {
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn {
whenever $conn.Supply(:bin) -> $buf {
my $promise = start {
say "-" x 70 ~ "\n" ~ $buf.decode('UTF-8').trim-trailing;
sleep 5;
my $response = "HTTP/1.0 200 OK\x0D\x0A\x0D\x0A";
$response ~= q:to/END/;
<html>
<head>
<title>Demo page</title>
</head>
<body>
<h1>Title here</h1>
<p>lorem ipsum here</p>
</body>
</html>
END
await $conn.write: $response.encode('utf-8');
$conn.close();
};
push @promises, $promise;
}
}
}
await @promises;
我正在尝试使用 Perl6 制作一个简单的非阻塞 Web 服务器,但很可能我不明白这里的某些内容。
示例:
#!/usr/bin/env perl6
use v6;
react {
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn {
whenever $conn.Supply(:bin) -> $buf {
say "-" x 70 ~ "\n" ~ $buf.decode('UTF-8').trim-trailing;
sleep 5; # HERE
my $response = "HTTP/1.0 200 OK\x0D\x0A\x0D\x0A";
$response ~= q:to/END/;
<html>
<head>
<title>Demo page</title>
</head>
<body>
<h1>Title here</h1>
<p>lorem ipsum here</p>
</body>
</html>
END
await $conn.write: $response.encode('utf-8');
$conn.close();
}
}
}
此处的示例与文档中的通用示例几乎相同https://docs.perl6.org/type/IO::Socket::Async
问题:
为什么页面不是并行提供的,而是按顺序提供给所有客户端的?
在这里回答我自己的问题。我是 perl6 的初学者,所以如果我在这里做一些奇怪的事情,请修复我。
使用 promises 似乎可以解决这个问题。我之前假设 IO::Socket::Async 会为我创建承诺,请求将由模块并行处理。
#!/usr/bin/env perl6
use v6;
my @promises;
react {
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn {
whenever $conn.Supply(:bin) -> $buf {
my $promise = start {
say "-" x 70 ~ "\n" ~ $buf.decode('UTF-8').trim-trailing;
sleep 5;
my $response = "HTTP/1.0 200 OK\x0D\x0A\x0D\x0A";
$response ~= q:to/END/;
<html>
<head>
<title>Demo page</title>
</head>
<body>
<h1>Title here</h1>
<p>lorem ipsum here</p>
</body>
</html>
END
await $conn.write: $response.encode('utf-8');
$conn.close();
};
push @promises, $promise;
}
}
}
await @promises;