Last active
August 29, 2015 14:16
-
-
Save brianmed/94a1e51ca99fda53266b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
### 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