Stupid-Websocket-Tricks-With-Perl



Stupid-Websocket-Tricks-With-Perl

0 0


Stupid-Websocket-Tricks-With-Perl

Some tricks you can do with websockets in Perl

On Github preaction / Stupid-Websocket-Tricks-With-Perl

Stupid Websocket Tricks

Why WebSockets?

Bidirectional

Unlike HTTP!

The Comet has Crashed!

Message Framing

JSON documents

Automatic Heartbeats

Mojolicious makes them easy!

Live Demo

Run perl shell.pl daemon -l 'http://*:7000'.Type in command and press "Run"

Run

                

Client-side

Connect to WebSocket

ws = new WebSocket( 'ws://localhost:7000/' );

Send the command

ws.onopen = function () {
    var cmd = $( '#command' ).val();
    ws.send( cmd );
};

Handle output

ws.onmessage = function ( msg ) {
    $( '#output' ).append( msg.data );
    // Scroll to the bottom of the output panel
    $( '#output' ).scrollTop( $( '#output' ).prop('scrollHeight') );
};

Server-side

Build WebSocket route

websocket '/' => sub {
    my ( $c ) = @_;

    $c->on( message => sub { ... } );
};

Run the command

my ( $c, $msg ) = @_;

my $pid = open my $fh, '-|', $msg;

Wrap in Mojo Stream

my $stream = Mojo::IOLoop::Stream->new( $fh );

Stream to WebSocket

$stream->on( read => sub {
    my ( $stream, $bytes ) = @_;
    $c->app->log->debug( "Sending output: $bytes" );
    $c->send( $bytes );
} );

Clean up

$stream->on( close => sub {
    kill KILL => $pid;
    close $fh;
} );

Add to IOLoop

my $sid = Mojo::IOLoop->stream( $stream );
$c->on( finish => sub {
    Mojo::IOLoop->remove( $sid );
} );

Mercury

WebSocket Message Patterns

Live Demo!

http://preaction.me:5000

Stupid Websocket Tricks