如何在 SharedWorker 中“仅一次”启动服务器发送事件来为任何打开的脚本推送消息?

Jun*_*ior 6 javascript jquery addeventlistener server-sent-events shared-worker

我有一个服务器发送事件(SSE)实现,几乎没有任何问题。我遇到的唯一问题是“一个用户可以与服务器建立多个连接”。基本上,如果用户打开多个 Web 浏览器选项卡,每个选项卡都会创建一个全新的服务器发送事件请求到服务器,这会导致单个用户运行许多请求。

为了解决这个问题,我想在 Javascript 的SharedWorker中运行 SSE 。

这意味着我只有一个 SSE 与 SharedWorker 进行通信。然后,每个页面/网络浏览器都会与 SharedWorker 进行通信。这给了我只允许每个用户一个 SSE 的优势。

这就是我的 SSE 目前在没有任何类型的工作人员的情况下的工作方式。

$(function(){
    //connect to the server to read messages
    $(window).load(function(){
        startPolling( new EventSource("poll.php") );
    });

    //function to listen for new messages from the server
    function startPolling(evtSource){

        evtSource.addEventListener("getMessagingQueue", function(e) {
            var data = JSON.parse(e.data);
            //handle recieved messages
            processServerData(data);

        }, false);

        evtSource.onerror = function(e) {
            evtSource.close();
        };

    }
});
Run Code Online (Sandbox Code Playgroud)

我希望运行相同的设置。然而,我想在 javascript 的 SharedWorker 中运行它,以消除每个用户拥有多个 SSE。

我正在努力实施 SharedWorker。这是我到目前为止所尝试的

我创建了一个名为的文件worker.js并将这段代码添加到其中

var ports = [] ;

onconnect = function(event) {

    var port = event.ports[0];
    ports.push(port);
    port.start();

    var serv = new EventSource(icwsPollingUrl) 
    serv.addEventListener("getMessagingQueue", function(e) {
        var data = JSON.parse(e.data);
        processServerData(data);

    }, false);

}
Run Code Online (Sandbox Code Playgroud)

然后在我想列出消息的页面上我有这个代码

$(function(){

    $(window).load(function(){

        var worker = new SharedWorker("worker.js");         


         worker.port.start();
         worker.port.onmessage = function(e) {
            console.log(e.data);
            console.log('Message received from worker');
         }

    });
});
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?

我究竟做错了什么?

我该如何纠正实施?

编辑

根据@Bergi 下面的评论,这是我的实现的更新版本,它仍然没有向连接器发布消息。我在代码中添加了注释,解释了对代码发生的情况的理解。

在登陆页面上,即index.php我像这样连接到我的 SharedWorker

$(function($){

    //establish connection to the shared worker
    var worker = new SharedWorker("/add-ons/icws/js/worker1.js");
        //listen for a message send from the worker
        worker.port.addEventListener("message",
                function(event) {
                    console.log(event.data);
                }
                , false
        );
        //start the connection to the shared worker
        worker.port.start();

 });
Run Code Online (Sandbox Code Playgroud)

worker1.js这是我的文件包含的代码

var ports = [] ;

//runs only when a new connection starts
onconnect = function(event) {

    var port = event.ports[0];
    ports.push(port);
    port.start();

    //implement a channel for a communication between the connecter and the SharedWorker
    port.addEventListener("message",
        function(event) { 
            listenForMessage(event, port);
        }
    );
}

//reply to any message sent to the SharedWorker with the same message but add the phrase "SharedWorker Said: " to it
listenForMessage = function (event, port) {
    port.postMessage("SharedWorker Said: " + event.data);

}

//runs every time and post the message to all the connected ports
function readNewMessages(){
    var serv = new EventSource(icwsPollingUrl) 
        serv.addEventListener("getMessagingQueue", function(e) {
        var queue = JSON.parse(e.data);

        notifyAllPorts(queue);

    }, false);
}

//check all open ports and post a message to each
function notifyAllPorts(msg){
    for(i = 0; i < ports.length; i++) {
        ports[i].postMessage(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的另一个版本worker1.js

var ports = [] ;

//runs only when a new connection starts
onconnect = function(event) {

    var port = event.ports[0];
    ports.push(port);
    port.start();

    //implement a channel for a communication between the connecter and the SharedWorker
    port.addEventListener("message",
        function(event) { 
            listenForMessage(event, port);
        }
    );
}

//reply to any message sent to the SharedWorker with the same message but add the phrase "SharedWorker Said: " to it
listenForMessage = function (event, port) {
    port.postMessage("SharedWorker Said: " + event.data);

}

readNewMessages();


//runs every time and post the message to all the connected ports
function readNewMessages(){
    console.log('Start Reading...');
    var serv = new EventSource(icwsPollingUrl);
        serv.addEventListener("getMessagingQueue", function(e) {
        var queue = JSON.parse(e.data);
        console.log('Message Received');
        console.log(queue);

        notifyAllPorts(queue);

    }, false);
}

//check all open ports and post a message to each
function notifyAllPorts(msg){
    for(i = 0; i < ports.length; i++) {
        ports[i].postMessage(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 3

也许已经晚了,但您可以在工作线程中创建一个 EventSource 单例,如下所示:

let ports = [];
var EventSourceSingleton = (function () {
    var instance;

    function createInstance() {
        var object = new EventSource('your path');
        return object;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

onconnect = function(e) {
    var port = e.ports[0];
    ports.push(port);
    var notifyAll = function(message){
        ports.forEach(port => port.postMessage(message));
    }

    var makeConnection = function (){
        var source = EventSourceSingleton.getInstance();

        source.onopen = function (e){
            var message = "Connection open"
            port.postMessage(message);
        }
        source.onerror = function(e){
            var message ="Ups you have an error";
            port.postMessage(message);
        }
        source.onmessage = function(e){
            // var message = JSON.parse(event.data);
            notifyAll(e.data);
        }
    }

    port.onmessage = function(e) {
        makeConnection();
    }
    port.start();
  }
Run Code Online (Sandbox Code Playgroud)

你可以像这样从外部调用它。

            var shWorker = new SharedWorker('woker.js');

            shWorker.port.onmessage = function (e) {
                console.log('Message received from worker');
                setmsj(e.data);
            }
            //Dummy message - For initialize
            shWorker.port.postMessage(true);
Run Code Online (Sandbox Code Playgroud)

在 // chrome://inspect/#workers 上享受调试的乐趣。