Skip to content

Commit

Permalink
better WebSocket example for Mojo::UserAgent
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Mar 18, 2013
1 parent aaef945 commit a1d870b
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions lib/Mojo/UserAgent.pm
Expand Up @@ -572,17 +572,18 @@ Mojo::UserAgent - Non-blocking I/O HTTP and WebSocket user agent
}
$delay->wait unless Mojo::IOLoop->is_running;
# Non-blocking WebSocket connection
$ua->websocket('ws://websockets.org:8787' => sub {
# Non-blocking WebSocket connection sending and receiving JSON text messages
use Mojo::JSON 'j';
$ua->websocket('ws://localhost:3000/echo.json' => sub {
my ($ua, $tx) = @_;
say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
$tx->on(finish => sub { say 'WebSocket closed.' });
$tx->on(message => sub {
my ($tx, $msg) = @_;
say "WebSocket message: $msg";
$tx->on(text => sub {
my ($tx, $bytes) = @_;
my $hash = j($bytes);
say "WebSocket message via JSON: $hash->{msg}";
$tx->finish;
});
$tx->send('hi there!');
$tx->send({text => j({msg => 'Hello World!'})});
});
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
Expand Down Expand Up @@ -999,14 +1000,18 @@ non-blocking.
$ua->websocket('ws://localhost:3000' => {DNT => 1} => sub {...});
Open a non-blocking WebSocket connection with transparent handshake, takes the
same arguments as L<Mojo::UserAgent::Transactor/"websocket">.
same arguments as L<Mojo::UserAgent::Transactor/"websocket">. The callback
will receive either a L<Mojo::Transaction::WebSocket> or
L<Mojo::Transaction::HTTP> object.
$ua->websocket('ws://localhost:3000/echo' => sub {
my ($ua, $tx) = @_;
say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
$tx->on(finish => sub { say 'WebSocket closed.' });
$tx->on(message => sub {
my ($tx, $msg) = @_;
say $msg;
say "WebSocket message: $msg";
$tx->finish;
});
$tx->send('Hi!');
});
Expand Down

0 comments on commit a1d870b

Please sign in to comment.