如何使Websocket API会话保持活动状态

时间:2014-07-31 23:37:20

标签: websocket bitcoin blockchain

我试图继续订阅blockchain.info websocket api以获取新块。我基本上将代码关闭http://www.websocket.org/echo.html并插入blockchain.info参数。它有效,但我发现它会在一段时间后自动断开连接。如何使会话保持活动状态?

<!DOCTYPE html>

<meta charset="utf-8" />

<title>WebSocket Test</title>

<script language="javascript" type="text/javascript">

  var wsUri = "wss://ws.blockchain.info/inv";
  var output;

  function init()
  {
    output = document.getElementById("output");
    testWebSocket();
  }



  function testWebSocket()
  {
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };
  }

  function onOpen(evt)
  {
    writeToScreen("CONNECTED");
    doSend("{\"op\":\"blocks_sub\"}");
  }

  function onClose(evt)
  {
    writeToScreen("DISCONNECTED");
  }

  function onMessage(evt)
  {
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
    //websocket.close();
  }

  function onError(evt)
  {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
  }

  function doSend(message)
  {
    writeToScreen("SENT: " + message); 
    websocket.send(message);
  }

  function writeToScreen(message)
  {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
  }


  window.addEventListener("load", init, false);

</script>

<h2>WebSocket Test</h2>

<div id="output"></div> 

1 个答案:

答案 0 :(得分:1)

我刚试过这个,看起来似乎有效:

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<script>

$(document).ready
(
    function(){

        initWebSocket();
    }
);
</script>

<script language="javascript" type="text/javascript">

function initWebSocket()
{
    //  init blockchain websocket (activity, blocks)
    var blockchain = new WebSocket('ws://ws.blockchain.info:8335/inv');

    blockchain.onerror = function (error){ console.log('connection.onerror',error); };

    blockchain.onopen = function () 
    {
        blockchain.send( JSON.stringify( {"op":"unconfirmed_sub"} ) );  //  subscribe to uncofirmed activity
    };

    blockchain.onmessage = function (message) 
    {
        var response = JSON.parse(message.data);

        var date = new Date(0);
        date.setUTCSeconds( response.x.time );

        if( response.op == "utx")
        {
            var amount = 0;

            for(var i=0;i<response.x.out.length;i++) 
                amount += response.x.out[i].value;

            //  amount is in satoshi
            //  1 BTC = 100,000,000 Satoshi (https://en.bitcoin.it/wiki/activity)
            response.amount = amount / 100000000;
        }


            console.log( response.op, response );



    };
}

主要从这里开始:http://bl.ocks.org/npedrini/6030317