Skip to content

Instantly share code, notes, and snippets.

@jberger
Created February 7, 2020 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/aec7c96bb70f1c61cf8c9fa3091de127 to your computer and use it in GitHub Desktop.
Save jberger/aec7c96bb70f1c61cf8c9fa3091de127 to your computer and use it in GitHub Desktop.
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