Created
December 9, 2013 04:22
-
-
Save jberger/7867359 to your computer and use it in GitHub Desktop.
example of a worker process communicating via websocket. not sure its the best idea
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
#!/usr/bin/env perl | |
use Mojo::Base -strict; | |
use Mojo::UserAgent; | |
use Mojo::IOLoop; | |
my $ua = Mojo::UserAgent->new; | |
my $url = 'ws://localhost:3000/ws'; | |
say "Connecting to $url"; | |
my $delay = Mojo::IOLoop->delay( | |
sub { | |
my $delay = shift; | |
$ua->websocket($url => $delay->begin); | |
}, | |
sub { | |
my ($delay, $tx) = @_; | |
$tx->on( finish => sub { say 'Closed'; Mojo::IOLoop->stop } ); | |
$tx->send('About to do stuff', $delay->begin(0)); | |
}, | |
sub { | |
# this step seems necessary to ensure that the loop isn't | |
# blocked before the message is really away | |
my ($delay, $tx) = @_; | |
my $end = $delay->begin(0); | |
Mojo::IOLoop->timer( 0.25 => sub { $end->($tx) } ); | |
}, | |
sub { | |
my ($delay, $tx) = @_; | |
my $end = $delay->begin(0); | |
sleep 3; # long running blocking process | |
$tx->send( 'Done', sub { $end->($tx) } ); | |
}, | |
sub { | |
my ($delay, $tx) = @_; | |
$tx->finish; | |
}, | |
); | |
Mojo::IOLoop->start; |
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
#!/usr/bin/env perl | |
use Mojolicious::Lite; | |
websocket '/ws' => sub { | |
my $c = shift; | |
$c->on( message => sub { | |
my ($c, $msg) = @_; | |
say "Got: $msg"; | |
}); | |
}; | |
app->start; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment