#!/usr/bin/perl ## run as: ./wbsckt.pl daemon use Mojolicious::Lite; ## Automatically enables "strict", "warnings", "utf8" and Perl 5.10 features; &startup; ##------------------------------------------------------------------- sub myapp{ my $tx=shift; $tx->send("Entering myapp."); foreach my $xx (0..3) { $tx->send("$xx..."); sleep(3); } $tx->send("Leaving myapp."); return "You should never see this."; } ##------------------------------------------------------------------- sub startup{ get '/' => sub { my $c=shift; $c->render('index'); }; get '/log2' => sub { my $c=shift; $c->render('log2'); }; websocket '/log3' => \&ws_log4; app->secrets(['password' => '8675309J']); app->start; } ##------------------------------------------------------------------- sub ws_log4{ my $self= shift; my $tx= $self->tx; my $ip= $tx->remote_address; app->log->debug("Client '$ip' connected"); $tx->send("Entering log4."); $self->on(&myapp($tx) => sub { my($ws,$msg)= @_; $ws->inactivity_timeout(50); $ws->send("Time is: " . scalar(localtime())); ## odd, we never see this output }); $self->on(finish => sub { my($c,$code,$reason)= @_; $c->app->log->debug("WebSocket closed with status $code."); }); $tx->send("Leaving log4."); } ##------------------------------------------------------------------- __DATA__ @@ index.html.ep Static Page

Index Page

This is a static page. For WebSockets example, click here.

@@ log2.html.ep WebSockets Example

%= javascript begin var ws = new WebSocket('<%= url_for('log3')->to_abs %>'); ws.onopen = function() { $('#result').text("Connection open."); //ws.send("Hi."); }; ws.onmessage = function (e) { $('#result').append( "\n" + e.data); }; % end