Skip to content

Commit

Permalink
Mojo::Transaction::WebSocket::send forces stringification on object
Browse files Browse the repository at this point in the history
  • Loading branch information
jberger committed Mar 21, 2013
1 parent a1d870b commit 80b23d8
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions Changes
Expand Up @@ -2,6 +2,7 @@
3.92 2013-03-18
- Improved documentation.
- Improved tests.
- Improved WebSocket send method to force stringification on object.

3.91 2013-03-17
- Improved bad charset handling in Mojo::DOM::HTML.
Expand Down
5 changes: 3 additions & 2 deletions lib/Mojo/Transaction/WebSocket.pm
Expand Up @@ -202,8 +202,8 @@ sub send {
: [1, 0, 0, 0, BINARY, $frame->{binary}];
}

# Text
elsif (!ref $frame) { $frame = [1, 0, 0, 0, TEXT, encode('UTF-8', $frame)] }
# Text or object (forcing stringification)
elsif (ref $frame ne 'ARRAY') { $frame = [1, 0, 0, 0, TEXT, encode('UTF-8', "$frame")] }

$self->once(drain => $cb) if $cb;
$self->{write} .= $self->build_frame(@$frame);
Expand Down Expand Up @@ -568,6 +568,7 @@ Resume C<handshake> transaction.
$ws = $ws->send({text => $bytes});
$ws = $ws->send([$fin, $rsv1, $rsv2, $rsv3, $op, $bytes]);
$ws = $ws->send($chars);
$ws = $ws->send(Mojo::ByteStream->new($chars));
$ws = $ws->send($chars => sub {...});
Send message or frame non-blocking via WebSocket, the optional drain callback
Expand Down
29 changes: 29 additions & 0 deletions t/mojo/websocket.t
Expand Up @@ -12,6 +12,7 @@ use Mojo::IOLoop;
use Mojo::Transaction::WebSocket;
use Mojo::UserAgent;
use Mojolicious::Lite;
use Mojo::ByteStream 'b';

# Max WebSocket size
{
Expand Down Expand Up @@ -113,6 +114,16 @@ websocket '/echo' => sub {
);
};

websocket '/echo_object' => sub {
my $self = shift;
$self->on(
message => sub {
my ($self, $msg) = @_;
$self->send(b($msg));
}
);
};

my $buffer = '';
websocket '/double_echo' => sub {
shift->on(
Expand Down Expand Up @@ -169,6 +180,24 @@ $ua->websocket(
Mojo::IOLoop->start;
like $result, qr!test1test2ws://localhost:\d+/!, 'right result';

# Plain WebSocket sending Mojo::ByteStream object
$ua->websocket(
'/echo_object' => sub {
my $tx = pop;
$tx->on(finish => sub { Mojo::IOLoop->stop });
$tx->on(
message => sub {
my ($tx, $msg) = @_;
$result = $msg;
$tx->finish;
}
);
$tx->send('test1');
}
);
Mojo::IOLoop->start;
is $result, 'test1', 'right result';

# Failed WebSocket connection
my ($code, $body, $ws);
$ua->websocket(
Expand Down

0 comments on commit 80b23d8

Please sign in to comment.