use warnings; use strict; use Mojolicious::Lite; use Mojo::IOLoop; # Define which template is rendered when the client goes to the base URLs. get '/' => 'deleteme'; # WebSocket reading device objects websocket '/ws' => sub { my $self = shift; # Opened $self->app->log->debug('WebSocket opened.'); # Increase inactivity timeout for connection a bit my $loop = Mojo::IOLoop->singleton; $loop->stream($self->tx->connection)->timeout(1000); # Closed $self->on(finish => sub { my ($self, $code, $reason) = @_; $self->app->log->debug("WebSocket closed with status $code."); }); # Incoming message $self->on(message => sub { # safely catch abort signals local $SIG{INT} = $SIG{TERM} = $SIG{__DIE__} = $SIG{__WARN__} = sub { $self->app->log->debug("Safely caught a signal in WebSocket message handler"); exit 0; }; }); $self->on(json => sub { my ($self, $hash) = @_; $self->app->log->debug("Got WebSocket JSON request"); # simmulate a handful of iterations of sitting in what otherwise would be an infinite loop for my $i (0 .. 10) { my $delay = $loop->delay( # First delay a bit sub { my $theDelay = shift; $loop->timer(5 => $theDelay->begin); $self->app->log->debug("Delay started"); }, # next do the Read and send back the data sub { $self->app->log->debug("Doing periodic useful thing"); } ); $delay->wait; exit if ($i > 10); } }); }; app->start;