Skip to content

Commit

Permalink
use promises in all cookbook WebSocket examples
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Dec 3, 2017
1 parent 220c6d2 commit 8d8809d
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions lib/Mojolicious/Guides/Cookbook.pod
Expand Up @@ -1389,7 +1389,7 @@ C<http+unix://> and C<ws+unix://> schemes, and pass along a percent encoded path
(C</> becomes C<%2F>) instead of a hostname.

use Mojo::UserAgent;
use Mojo::IOLoop;
use Mojo::Promise;

# GET request via UNIX domain socket "/tmp/foo.sock"
my $ua = Mojo::UserAgent->new;
Expand All @@ -1400,20 +1400,24 @@ C<http+unix://> and C<ws+unix://> schemes, and pass along a percent encoded path
say $tx->result->body;

# WebSocket connection via UNIX domain socket "/tmp/baz.sock"
$ua->websocket('ws+unix://%2Ftmp%2Fbaz.sock/echo' => sub {
my ($ua, $tx) = @_;
$ua->websocket_p('ws+unix://%2Ftmp%2Fbaz.sock/echo')->then(sub {
my $tx = shift;

say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
my $promise = Mojo::Promise->new;
$tx->on(finish => sub { $promise->resolve });

$tx->on(message => sub {
my ($tx, $msg) = @_;
say "WebSocket message: $msg";
$tx->finish;
});

$tx->send('Hi!');
});
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

return $promise;
})->catch(sub {
my $err = shift;
warn "WebSocket error: $err";
})->wait;

You can set the C<Host> header manually to pass along a hostname.

Expand Down

0 comments on commit 8d8809d

Please sign in to comment.