有没有人有一个使用websocket将数据推送到客户端的例子?我能找到的唯一例子是浏览器向服务器发送数据并且服务器执行消息回调。我假设有一个技巧让WS执行101交换机协议并准备服务器发送()消息。我能做的最好的事情就是让消息留在WS中,直到控制器的路由方法退出。
Mojolicious Controller
package WebLOC::Controller::Progress;
use Mojo::Base 'Mojolicious::Controller';
sub websocket {
my $self = shift;
my $guid = $self->stash('guid');
$self->app->log->info("$$ Creating WebSocket: $guid");
$self->on( finish => sub { shift->app->log->debug("$$ Finished $guid") }
);
$self->on( drain => sub { shift->app->log->debug("$$ drained $guid") } );
my $websocket = $self->tx;
$websocket->send('here i am');
sleep 3; # This is an example. Use timer instead of sleep
$websocket->send('here i am');
sleep 3; # This is an example. Use timer instead of sleep
$websocket->send('here i am');
$self->finish;
}
1;
Mojolicious Log
[Tue Dec 5 16:05:40 2017] [debug] Routing to controller "WebLOC::Controller::Progress" and action "websocket"
[Tue Dec 5 16:05:40 2017] [info] 12255 Creating WebSocket: EF209EA8-D9DB-11E7-A437-5FBE6A63D34C
[Tue Dec 5 16:05:40 2017] [debug] 101 Switching Protocols (0.008479s, 117.938/s)
[Tue Dec 5 16:05:46 2017] [debug] 200 OK (6.037878s, 0.166/s)
[Tue Dec 5 16:05:46 2017] [debug] 12255 drained EF209EA8-D9DB-11E7-A437-5FBE6A63D34C
[Tue Dec 5 16:05:46 2017] [debug] 12255 Finished EF209EA8-D9DB-11E7-A437-5FBE6A63D34C
查看Controller代码,我的代码中的第一个$ self-> on()设置由$ c-rendered(101)生成101调试日志条目,但101实际上并没有直到6秒延迟后才到浏览器。这个问题似乎与this有关,但没有解决方案,我无法发表评论。