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

Hi, here is working websocket code using Net::Async::WebSocket::Client and occasionally the websocket will drop. The websocket API heartbeat feed sends a JSON object every second. If there is no data for two or three seconds it is okay to reconnect the session assuming no other way to detect the socket is down.

What would be the proper way to go about detecting a dropped/closed web socket and auto-reconnecting?

I think the answer has something to do with Future but I don't understand how it would go together.

#!/usr/bin/perl use warnings; use strict; use IO::Async::Loop; use Net::Async::WebSocket::Client; use JSON::XS qw( decode_json encode_json ); use Data::Dumper; my $client = Net::Async::WebSocket::Client->new( on_text_frame => sub { my ( $self, $json ) = @_; my $data = decode_json $json; # this is how we detect a heartbeat #return if $data->{type} eq 'heartbeat'; print Dumper $data; }, ); my $loop = IO::Async::Loop->new; $loop->add( $client ); $client->connect( url => "wss://ws-feed.gdax.com", )->then( sub { $client->send_text_frame( encode_json { type => "subscribe", product_ids => [ "ETH-USD", ], channels => [ 'heartbeat', ] } ); } )->get; $loop->run;

Replies are listed 'Best First'.
Re: Auto Re-Connect Websocket Net::Async::WebSocket::Client
by ownlifeful (Beadle) on Jul 07, 2018 at 16:32 UTC

    Thanks for posting this code. I don't have an answer to your question, but I found your code very useful.