2017-09-20 14 views
0

ウェブソケットに接続してデータを取得するChrome拡張機能をビルドします。私は、ユーザーがpopup.htmlからオプションを選択する方法を構築しようとしており、接続がどのwebsocketに変更されるかを変更します。これはうまくいきます。ウェブソケットを正しく閉じる方法

私の問題は、オプションを選択すると、新しい接続がそのwebsocketに行われますが、以前のものはデータを返すことです。私は新しい接続を開く前に、以前の接続を終了したいと思います。

popup.js(ラジオボタンの変更に新しい値を格納する)

$(function() { 
     $("input:radio[name=exc]").change(function() { 
      chrome.storage.local.set({'checked':this.value}, function() { 
      }); 
     }); 
    }); 

update.js(私はpreivousの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.を取得しており、データは受信されていません。

答えて

1

あなたのコードは現在意味がありません。新しいサービスを設定した後すぐに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 
    } 
0

close() methodは公式のWebSocket MDNドキュメントにあります:もしあれば

近い() は、WebSocketの接続または接続の試行を終了します。接続がすでに閉じられている場合、このメソッドは何も行いません。

void close(
    in optional unsigned short code, 
    in optional DOMString reason 
); 

また、正しいポートを使用していることを確認してください。その他の詳細SO post

関連する問題