| 1 | package PAGI::App::WebSocket::Echo; | ||
| 2 | $PAGI::App::WebSocket::Echo::VERSION = '0.002001'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Future::AsyncAwait; | ||
| 6 | |||
| 7 | =head1 NAME | ||
| 8 | |||
| 9 | PAGI::App::WebSocket::Echo - Echo WebSocket messages back to sender | ||
| 10 | |||
| 11 | =head1 SYNOPSIS | ||
| 12 | |||
| 13 | use PAGI::App::WebSocket::Echo; | ||
| 14 | |||
| 15 | my $app = PAGI::App::WebSocket::Echo->new->to_app; | ||
| 16 | |||
| 17 | =cut | ||
| 18 | |||
| 19 | sub new { | ||
| 20 | my ($class, %args) = @_; | ||
| 21 | |||
| 22 | return bless { | ||
| 23 | on_connect => $args{on_connect}, | ||
| 24 | on_disconnect => $args{on_disconnect}, | ||
| 25 | }, $class; | ||
| 26 | } | ||
| 27 | |||
| 28 | sub to_app { | ||
| 29 | my ($self) = @_; | ||
| 30 | |||
| 31 | my $on_connect = $self->{on_connect}; | ||
| 32 | my $on_disconnect = $self->{on_disconnect}; | ||
| 33 | |||
| 34 | return async sub { | ||
| 35 | my ($scope, $receive, $send) = @_; | ||
| 36 | die "Unsupported scope type: $scope->{type}" if $scope->{type} ne 'websocket'; | ||
| 37 | |||
| 38 | # Accept the connection | ||
| 39 | await $send->({ type => 'websocket.accept' }); | ||
| 40 | |||
| 41 | $on_connect->($scope) if $on_connect; | ||
| 42 | |||
| 43 | # Echo loop | ||
| 44 | while (1) { | ||
| 45 | my $event = await $receive->(); | ||
| 46 | |||
| 47 | if ($event->{type} eq 'websocket.receive') { | ||
| 48 | # Echo back - preserve text vs binary | ||
| 49 | if (exists $event->{text}) { | ||
| 50 | await $send->({ | ||
| 51 | type => 'websocket.send', | ||
| 52 | text => $event->{text}, | ||
| 53 | }); | ||
| 54 | } elsif (exists $event->{bytes}) { | ||
| 55 | await $send->({ | ||
| 56 | type => 'websocket.send', | ||
| 57 | bytes => $event->{bytes}, | ||
| 58 | }); | ||
| 59 | } | ||
| 60 | } elsif ($event->{type} eq 'websocket.disconnect') { | ||
| 61 | $on_disconnect->($scope, $event->{code}) if $on_disconnect; | ||
| 62 | last; | ||
| 63 | } | ||
| 64 | } | ||
| 65 | }; | ||
| 66 | } | ||
| 67 | |||
| 68 | 1; | ||
| 69 | |||
| 70 | __END__ |