经过进一步研究,我决定实施网络工作者。
在这一点上,我取得了成功,我想为未来的读者添加一个我坚持的重要文章。
在我的 worker.js 文件中,我将它放在顶部以启动。如果我不这样做,importScripts 函数会引发错误。
同样为了帮助,这是我的 worker.js 文件中有效的框架代码。来自 html 页面的消息处理与从服务器接收到的 ws 消息是分开的。您可以从 html 页面启动、停止工作程序。
所有选项卡都会从工作人员那里获取消息,每个页面都需要根据需要处理消息。
我还使用了强大的 websockets,因此它会自动从这个 github 重新连接,因为这段代码可以与 web 工作者一起使用并得到维护。还有一个同名项目在本文发布时尚未更新。reconnecting-websockets 不支持 web worker,你会得到一个错误。- https://github.com/nathanboktae/robust-websocket
html
<script>
document.addEventListener('DOMContentLoaded', init);
function init(){
worker = new Worker('js/ws_worker.js');
worker.addEventListener('message', workerMessaged);
worker.postMessage({ "args": '<username_admin>', "cmd": 'start', "url": '127.0.0.1:8000' });
worker.postMessage({ "message": 'Initialize new worker'});
console.log('Message posted to worker, start');
}
// Received a json message from the Worker, process it.
function workerMessaged(ev){
console.log('Message received from worker');
console.log(ev.data);
worker.postMessage({ "cmd": 'message', "message": 'Sending reply over ws'});
}
worker.js
// proper initialization
if( 'function' === typeof importScripts) {
importScripts('robust-websocket.js');
var WebSocket;
self.addEventListener("message", function(e) {
var args = e.data.args;
var cmd = e.data.cmd;
var roomName = e.data.args;
var url = e.data.url;
var message = e.data;
// Code to process ws messages from the server
WebSocket.onmessage = function(event) {
console.log(" WebSocket message received: " + event.data, event);
self.postMessage(event.data);
};
WebSocket.onerror = function(event) {
console.log(" WebSocket message received: " + event.data, event);
self.postMessage(event.data);
};
if (cmd === 'start') {
WebSocket = new RobustWebSocket(
'ws://' + url +
'/ws/' + roomName + '/');
console.log('Connected via websockets');
/* Send initial message to open the connection and finalize the ws object*/
WebSocket.onopen = function() {
var obj = { "message": "hello" };
var json = JSON.stringify(obj);
WebSocket.send(json);
};
} else if (cmd === 'stop') {
WebSocket.onclose = function() {
console.log('Closing WebSocket');
WebSocket.close();
console.log('Closed WebSocket');
console.log('Terminating Worker');
self.close(); // Terminates the worker.
};
} else if (cmd === 'message') {
WebSocket.onopen = function() {
var json = JSON.stringify(message);
WebSocket.send(json);
};
console.log('message sent over websocket');
console.log('message');
} else {
console.log('logging error ' + e.data);
console.log(e.data);
self.postMessage('Unknown command: ');
}
}, false);
};