gpt4 book ai didi

sockets - 简单的非阻塞网络服务器

转载 作者:行者123 更新时间:2023-12-03 11:53:06 25 4
gpt4 key购买 nike

我正在尝试使用 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 的初学者,所以如果我在这里做一些奇怪的事情,请修复我。

使用 Promise 似乎可以解决这个问题。我之前假设 IO::Socket::Async 会为我创建 promise ,并且请求将由模块并行处理。

#!/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;

关于sockets - 简单的非阻塞网络服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com