Mojolicious websocket usage

我只是一个虾纸丫 提交于 2019-12-12 20:32:55

问题


Given the code below, how do I send a message to the client, via the websocket opened for '/wsinit', from within 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;

Please disregard the following superfluous verbiage the purpose of which is satisfy stackoverflow's details/code requirements which are currently preventing me from posting my question.


回答1:


You will need to connect to the websocket via javascript in the client-side code. The code you have looks like it should work for sending to the client once the connection is established.

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

If the question is about the dosomething method, I don't understand the question. Call it as a method in the action, or else connect it as the action for some other route. If that doesn't answer the question, please clarify your request workflow.



来源:https://stackoverflow.com/questions/17284382/mojolicious-websocket-usage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!