Is an EventSource (SSE) supposed to try to reconnect indefinitely?

前端 未结 6 1991
余生分开走
余生分开走 2021-01-30 09:22

I\'m working on a project utilizing Server-Sent-Events and have just run into something interesting: connection loss is handled differently between Chrome and Firefox.

O

6条回答
  •  离开以前
    2021-01-30 09:46

    here's another variation folks might like

    let events = null;
    
    function connect() {
        events = new EventSource("/some/url");
        events.onerror = function() {
            events.close();
        }
    }
    connect();
    
    let reconnecting = false;
    setInterval(() => {
        if (events.readyState == EventSource.CLOSED) {
            reconnecting = true;
            console.log("reconnecting...");
            connect();
        } else if (reconnecting) {
            reconnecting = false
            console.log("reconnected!");
        }
    }, 3000);
    

提交回复
热议问题