Web socket API session automatically disconnecting

0 votes

Working on the code from: http://www.websocket.org/echo.html and trying to keep subscribed to blockchain.info websocket api for new blocks. How do I keep the websocket API session alive if it keeps disconnecting automatically?

Following is the code:

<!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> 
Aug 29, 2018 in Blockchain by sabby
• 4,370 points
3,155 views

2 answers to this question.

0 votes

This code seems to work just fine:

<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 );



    };
}
answered Aug 29, 2018 by Christine
• 15,790 points
0 votes
Yes, the code given by Christine works! To know more, you can visit: http://bl.ocks.org/npedrini/6030317
answered Aug 29, 2018 by digger
• 26,740 points

Related Questions In Blockchain

+1 vote
1 answer

Transaction using Blockchain wallet APi

Each transaction requires a fee to be ...READ MORE

answered Jun 19, 2018 in Blockchain by Perry
• 17,100 points
760 views
+2 votes
1 answer

Blockchain declining my API key and I cannot understand why.

It's quite easy. Request the API key using ...READ MORE

answered Apr 3, 2018 in Blockchain by Christine
• 15,790 points
2,052 views
0 votes
1 answer

Curl Script Usage in Ethereum Blockcypher's API

You should store and keep the private ...READ MORE

answered May 28, 2018 in Blockchain by Christine
• 15,790 points
1,433 views
+1 vote
1 answer

Protocols used in a distributed/dlt system for the nodes to establish communication

yes all are over TCP/IP connections secured ...READ MORE

answered Aug 6, 2018 in Blockchain by aryya
• 7,460 points
1,428 views
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,790 points
1,923 views
0 votes
1 answer

Hyperledger Sawtooth vs Quorum in concurrency and speed Ask

Summary: Both should provide similar reliability of ...READ MORE

answered Sep 26, 2018 in IoT (Internet of Things) by Upasana
• 8,620 points
1,451 views
+1 vote
1 answer

Unable to send payment using API. Please help.

Firstly, check your passwords, your API code and your wallet ...READ MORE

answered Apr 3, 2018 in Blockchain by Christine
• 15,790 points
1,149 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP