Created
February 7, 2020 14:44
-
-
Save jberger/aec7c96bb70f1c61cf8c9fa3091de127 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Mojo::Base -strict, -signatures; | |
use Mojolicious; | |
use Mojo::IOLoop; | |
use Mojo::Server::Daemon; | |
use Mojo::UserAgent; | |
# mock external websocket application | |
# waits 5s after connection then sends time and closes | |
my $external = Mojolicious->new; | |
$external->routes->websocket('/' => sub ($c) { | |
my $tx = $c->tx; | |
my $t = Mojo::IOLoop->timer(5 => sub { | |
$c->send({json => {time => time}}, sub { $tx->finish }); | |
}); | |
$c->on(close => sub { Mojo::IOLoop->remove($t); undef $tx }); | |
}); | |
my $server = Mojo::Server::Daemon->new(app => $external, silent => 1); | |
my $port = $server->listen(['http://127.0.0.1'])->start->ports->[0]; | |
# this is your actual app | |
my $app = Mojolicious->new; | |
my $r = $app->routes; | |
my $ua = Mojo::UserAgent->new; | |
$r->get('/' => sub ($c) { | |
$c->render_later; | |
my $tx = $c->tx; | |
$ua->websocket("ws://127.0.0.1:$port/" => sub ($, $ws_tx) { | |
$ws_tx->on(json => sub ($, $data) { | |
$c->render(text => $data->{time}); | |
undef $tx; | |
}); | |
}); | |
}); | |
$app->start; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment