Perl 迷人的websocket用法

Perl 迷人的websocket用法,perl,mojolicious,Perl,Mojolicious,给定下面的代码,如何通过为“/wsinit”打开的websocket从Fu::Bar::dosomething中向客户端发送消息 package Fu; use Mojo::Base 'Mojolicious'; sub startup { my $r = shift->routes; $r->get('/')->to(controller => 'bar', action => 'init'); $r->websocket('/

给定下面的代码,如何通过为“/wsinit”打开的websocket从Fu::Bar::dosomething中向客户端发送消息

package Fu;
use Mojo::Base 'Mojolicious';

sub startup
{
    my $r = shift->routes;

    $r->get('/')->to(controller => 'bar', action => 'init');

    $r->websocket('/wsinit')->to(controller => 'bar', action => 'wsinit');

    $r->get('/dosomething')->to(controller => 'bar', action => 'dosomething');
}

1;

# -- ^L
# -- 

package Fu::Bar;
use Mojo::Base 'Mojolicious::Controller';

sub init
{
    my $self = shift;
    $self->render(text => 'init');
}
sub wsinit
{
    my $self = shift;
    $self->app->log->debug( 'Websocket opened.' );
    $self->send({json => {fu => 'bar'}});
}
sub dosomething
{
    my $self = shift;
}

1;

请忽略以下多余的措辞,其目的是满足stackoverflow的详细信息/代码要求,这目前阻止我发布我的问题。

您需要通过中的javascript连接到websocket。您拥有的代码看起来应该可以在连接建立后发送到客户端

#!/usr/bin/env perl

use Mojolicious::Lite;

any '/' => 'index';

websocket '/ws' => sub {
  my $c = shift;
  $c->send({ json => { foo => 'bar' } });
};

app->start;

__DATA__

@@ index.html.ep

<!DOCTYPE html>
<html>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
  <p id="result"></p>
  %= javascript begin
    var ws = new WebSocket('<%= url_for('ws')->to_abs %>');
    ws.onmessage = function (e) {
      $('#result').text(e.data)
    };
  % end
</body>
</html>
#/usr/bin/env perl
使用mojolicous::Lite;
任何“/”=>“索引”;
websocket'/ws'=>sub{
我的$c=班次;
$c->send({json=>{foo=>'bar'});
};
应用程序->启动;
__资料__
@@index.html.ep

%=javascript开始 var ws=新的WebSocket('to_abs%>'); ws.onmessage=函数(e){ $(“#结果”).text(e.data) }; %结束

如果问题是关于
dosomething
方法,我不理解这个问题。将其作为操作中的方法调用,或者将其作为其他路由的操作连接。如果这还不能回答问题,请澄清您的请求工作流

什么语言的代码?Perl?