Skip to content

Instantly share code, notes, and snippets.

@brianmed
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brianmed/94a1e51ca99fda53266b to your computer and use it in GitHub Desktop.
Save brianmed/94a1e51ca99fda53266b to your computer and use it in GitHub Desktop.
### SERVER
use Mojolicious::Lite;
use 5.20.0;
use experimental 'signatures';
websocket '/code.json' => sub ($c) {
$c->app->log->debug('WebSocket opened');
$c->inactivity_timeout(300);
$c->on(message => sub ($c, $msg) {
$c->app->log->debug("msg: $msg");
});
$c->on(json => sub ($tx, $hash) {
$c->app->log->debug("WebSocket message via JSON: $$hash{msg}");
});
$c->on(finish => sub ($c, $code) {
$c->app->log->debug("WebSocket closed with status $code");
});
};
app->start;
### CLIENT
use 5.20.0;
use Mojo::UserAgent;
our $ua;
our $tx;
$ua = Mojo::UserAgent->new;
$tx = $ua->websocket("ws://$ENV{HOST}:3001/code.json");
die ($tx->error->{message}) unless $tx->is_websocket;
$tx->on(finish => sub {
my ($tx, $code, $reason) = @_;
say "WebSocket closed with status $code.";
});
$tx->on(message => sub {
my ($tx, $msg) = @_;
say "WebSocket message: $msg";
});
$tx->send(json => {msg => "Hello"});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment