[英]How to properly close websockets
我正在構建一個Chrome擴展程序,該擴展程序可以連接到websockets並檢索數據。 我正在嘗試建立一種方法,使用戶從popup.html中選擇一個選項,並將其更改為將建立連接的websocket。 一切正常。
我的問題是,選擇一個選項后,將對該WebSocket建立新的連接,但先前的WebSocket會繼續返回數據。 我想先關閉以前的連接再打開一個新的連接。
popup.js(在單選按鈕上更改會存儲新值)
$(function() {
$("input:radio[name=exc]").change(function() {
chrome.storage.local.set({'checked':this.value}, function() {
});
});
});
update.js(接收新選擇的單選按鈕,我正在嘗試關閉以前的websocket)
chrome.storage.onChanged.addListener(function(changes, namespace) {
chrome.storage.local.get("checked", function(data) {
if(data.checked == "foo") {
var ws = new WebSocket('wss://api.foo.com/ws');
ws.onopen = function() {
ws.send(JSON.stringify({"event":"test", "channel":"test"}));
};
ws.onmessage = function(msg) {
var price = response[7];
if(hb != "hb" && typeof hb != 'undefined') {
price = price.toString();
chrome.extension.sendMessage(price);
}
};
ws.close();
}
else if(data.checked == "bar") {
var pusher = new Pusher('xxxxxxxxxxxxx');
var tradesChannel = pusher.subscribe('test'),
child = null;
tradesChannel.bind('test', function (data) {
var price = data.price;
if(typeof data.price != 'undefined') {
price = price.toString();
chrome.extension.sendMessage(price);
}
});
pusher.disconnect();
}
});
});
如果按WebSocket connection to 'wss://api.foo.com/ws' failed: WebSocket is closed before the connection is established.
保留代碼,則將WebSocket connection to 'wss://api.foo.com/ws' failed: WebSocket is closed before the connection is established.
並且沒有接收到數據。
當前的代碼沒有意義; 您在設置新服務后會立即致電close
/ disconnect
。
此外,您將丟失對推送服務的引用,因為它僅存儲在本地變量中。 這需要作為狀態存儲在某處-全局狀態很簡單,也許您可以對其進行更好的設計。
一個簡單的解決方案如下所示:
var ws; // We need it later, can't be a local variable
/* ... */
if(data.checked == "foo") {
if(ws) { ws.close(); ws = null; }
ws = new WebSocket('wss://api.foo.com/ws');
ws.onopen = function() {
ws.send(JSON.stringify({"event":"test", "channel":"test"}));
};
ws.onmessage = function(msg) {
var price = response[7];
if(hb != "hb" && typeof hb != 'undefined') {
price = price.toString();
chrome.extension.sendMessage(price);
}
};
// Don't close the new one here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.