Ric*_*rth 10 websocket cro raku
简而言之:我使用 Cro 和 websocket 在互联网服务器上创建了一项服务。使用 Cro 示例非常简单。当页面作为本地主机时,从 HTML 页面发送和接收数据时没有问题。当使用 https 提供页面时,无法建立 websocket。wss协议如何与Cro一起使用?
更新:安装cro并运行后cro stub :secure,service.p6 还有一些文档中未明确的代码。
更多详细信息:我有一个在互联网服务器上运行的 docker 文件,Cro 设置为侦听 35145,因此 docker 命令是docker --rm -t myApp -p 35145:35145
服务文件包含
use Cro::HTTP::Log::File;
use Cro::HTTP::Server;
use Cro::HTTP::Router;
use Cro::HTTP::Router::WebSocket;
my $host = %*ENV<RAKU_WEB_REPL_HOST> // '0.0.0.0';
my $port = %*ENV<RAKU_WEB_REPL_PORT> // 35145;
my Cro::Service $http = Cro::HTTP::Server.new(
http => <1.1>,
:$host,
:$port,
application => routes(),
after => [
Cro::HTTP::Log::File.new(logs => $*OUT, errors => $*ERR)
]
);
$http.start;
react {
whenever signal(SIGINT) {
say "Shutting down...";
$http.stop;
done;
}
}
sub routes() {
route {
get -> 'raku' {
web-socket :json, -> $incoming {
supply whenever $incoming -> $message {
my $json = await $message.body;
if $json<code> {
my $stdout, $stderr;
# process code
emit({ :$stdout, :$stderr })
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 HTML 中,我有一个带有 id 的 textarea 容器raku-code。js 脚本在 DOM 准备好后触发的处理程序中具有以下内容(我在脚本中的其他位置设置了 websocketHost 和 websocketPort):
const connect = function() {
// Return a promise, which will wait for the socket to open
return new Promise((resolve, reject) => {
// This calculates the link to the websocket.
const socketProtocol = (window.location.protocol === 'https:' ? 'wss:' : 'ws:');
const socketUrl = `${socketProtocol}//${websocketHost}:${websocketPort}/raku`;
socket = new WebSocket(socketUrl);
// This will fire once the socket opens
socket.onopen = (e) => {
// Send a little test data, which we can use on the server if we want
socket.send(JSON.stringify({ "loaded" : true }));
// Resolve the promise - we are connected
resolve();
}
// This will fire when the server sends the user a message
socket.onmessage = (data) => {
let parsedData = JSON.parse(data.data);
const resOut = document.getElementById('raku-ws-stdout');
const resErr = document.getElementById('raku-ws-stderr');
resOut.textContent = parsedData.stdout;
resErr.textContent = parsedData.stderr;
}
Run Code Online (Sandbox Code Playgroud)
当使用此 JS 脚本设置 HTML 文件并在本地提供服务时,我可以将数据发送到在互联网服务器上运行的 Cro 应用程序,并且 Cro 应用程序(在 docker 映像中运行)处理并返回位于右侧的数据HTML 容器。使用 Firefox 和开发人员工具,我可以看到 ws 连接已创建。
但是,当我通过 Apache 提供同一文件(强制通过 https 访问)时,Firefox 会发出无法创建“wss”连接的错误。此外,如果我在 JS 脚本中强制使用“ws”连接,Firefox 会阻止创建非安全连接。
a) 如何更改 Cro 编码以允许 wss?从 Cro 文档来看,我似乎需要添加一个 Cro::TLS 侦听器,但不清楚在哪里实例化侦听器。b) 如果这是在 docker 文件中,我是否需要在映像中包含秘密加密密钥,这不是我想要做的事情?c) 有没有办法将 Cro 应用程序放在 Apache 服务器后面,以便 Apache 解密/加密 Websocket?
如何更改 Cro 编码以允许 wss?从 Cro 文档来看,我似乎需要添加一个 Cro::TLS 侦听器,但不清楚在哪里实例化侦听器。
只需将所需的参数传递给 Cro::HTTP::Server,它就会为您设置侦听器。
如果这是在 docker 文件中,我是否需要在映像中包含秘密加密密钥,这不是我想要做的事情?
不。您可以将它们保存在一个卷中,或者从主机绑定安装它们。
有没有办法将 Cro 应用程序放在 Apache 服务器后面,以便 Apache 解密/加密 Websocket?
是的,与任何其他应用程序相同。使用mod_proxy、mod_proxy_wstunnel和ProxyPass命令。其他前端(例如 nginx、haproxy 或 envoy)也可以完成这项工作。