简体   繁体   中英

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!

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);
    });
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM