Renato Francia
Renato Francia

Reputation: 813

Node http client reconnect after connection timeout

I've been using a package called icy that uses the Http Client from Node v8.11.3.

I'm connecting to a streamer Icecast server with continuous audio.

The code looks like the following:

icy.get(url, (res) => {

  res.on('end', (e) => console.log('connection ends')); // end of connection
  res.on('metadata' => () => {...}); // metadata handler
}

The problem comes when the Icecast server restarts or times out.

I want the function to try to reconnect after timeout but haven't found an option to it in the docs.

Any help would be appreciated.

Cheers!

Upvotes: 0

Views: 746

Answers (1)

stdob--
stdob--

Reputation: 29167

You need to catch the error event and the finish of the stream event:

const icy = require('icy');

var url = 'http://ice4.lagrosseradio.info/lagrosseradio-metal-024.mp3';

(function play() {
    this.count = 0
    this.timeout

    function restart(error) {
        this.count++;
        console.error(this.count + ' reconnect...');
        clearTimeout(this.timeout);
        this.timeout = setTimeout(play, 100);
    }

    const client = icy.get(url, function(res) {
        res.on('metadata', function(metadata) {
            console.log(icy.parse(metadata));
        });
        client.on('close', function(error) {
            restart(error);
        });
    });
    client.on('error', function(error) {
        restart(error);
    });
})();

Upvotes: 2

Related Questions