http://www.perlmonks.org?node_id=1201155

Black Vagrant has asked for the wisdom of the Perl Monks concerning the following question:

Good day, how i can get all connected clients to my websocket server for send "global" message For example:
my $server = AnyEvent::WebSocket::Server->new(); my $tcp_server = tcp_server undef, 3000, sub { my ($fh) = @_; $server->establish($fh)->cb( sub { my $connection = eval { shift->recv }; ... $connection->on( each_message => sub { my ($connection, $message) = @_; # how i can get all connections # and then send message to all clients? foreach my $connection (@all_connections) { $connection->send($message) or die $!; } } ); ... } ); };

Replies are listed 'Best First'.
Re: AnyEvent::WebSocket::Server get all connections
by roboticus (Chancellor) on Oct 11, 2017 at 12:44 UTC

    Black Vagrant:

    I've not used AnyEvent::WebSocket::Server before, but a brief review of the documentation suggests that you should be able to add your connections to a structure when you create them and remove them when the connection closes, something like this:

    . . . # My box o' global connections my @cnx; . . . $server->establish($fh)->cb( sub { my $connection = eval { shift->recv }; # Add new connection to the box push @cnx, $connection; # Remove connection when it closes $connection->on(finish => sub { @cnx = grep { $_ ne $connection } @cnx; } . . . } ); . . . sub send_global_message { my $msg = shift; for my $c (@cnx) { $c->send($msg); } }

    Note: standard warranty applies--Untested, if broken you can keep both pieces, can cause hair loss, impotence, edema, etc.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      Many thanks