【问题标题】:Mojolicious websocket usageMojolicious websocket 使用
【发布时间】:2013-06-24 20:21:29
【问题描述】:

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

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 的详细信息/代码要求。

【问题讨论】:

  • 什么语言的代码? Perl?

标签: perl mojolicious


【解决方案1】:

您需要通过client-side code 中的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>

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

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    相关资源
    最近更新 更多