Bitcoin Forum

Economy => Web Wallets => Topic started by: Skull1234567 on July 31, 2014, 01:40:57 PM



Title: Blockchain.info Websocket API
Post by: Skull1234567 on July 31, 2014, 01:40:57 PM
Hi,

I'm trying to get the blockchain.info websocket api to connect for subscribing to blocks. I basically took the code off http://www.websocket.org/echo.html and plugged in blockchain.info parameters. It works, but I'm finding that after a while it will automatically disconnect. How do I keep the session alive?
Here's my code:
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>



Title: Re: Blockchain.info Websocket API
Post by: bitpop on August 02, 2014, 09:11:16 AM
Their cloud flare might be interfering causing the circuit to break. Why can't you just reload the page on an error?


Title: Re: Blockchain.info Websocket API
Post by: Skull1234567 on August 02, 2014, 02:23:18 PM
Their cloud flare might be interfering causing the circuit to break. Why can't you just reload the page on an error?
Because I want to have a subscription to all new blocks (similar to how they display on their homepage). I'm positive that it isn't cloudflare that stops me, it's blockchain.info's servers that think I'm not there anymore (because they haven't heard anything for a while).


Title: Re: Blockchain.info Websocket API
Post by: micaman on August 02, 2014, 02:39:23 PM
I've had a couple of problems in the past when implementing that script and couldn't figure out what was causing it.
Instead I've found a similar approach, which seems to work well, you can try it out.

Code:
function initWebSocket()
{
// init blockchain websocket (activity, blocks)
var blockchain = new WebSocket('ws://ws.blockchain.info/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.send( JSON.stringify( {"op":"blocks_sub"} ) ); // subscribe to new blocks
};
 
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;
response.type = TYPE_TRANSACTION;
response.index = index++;
}
else if( response.op == "block" )
{
response.type = TYPE_BLOCK;
response.amount = Math.round( response.x.height / 10000 );
}

if( DEBUG )
console.log( response.op, response );

response.date = date;

};

You can find the source here:
https://gist.github.com/npedrini/6030317


Title: Re: Blockchain.info Websocket API
Post by: Skull1234567 on August 03, 2014, 07:46:17 PM
I've had a couple of problems in the past when implementing that script and couldn't figure out what was causing it.
Instead I've found a similar approach, which seems to work well, you can try it out.

Code:
function initWebSocket()
{
// init blockchain websocket (activity, blocks)
var blockchain = new WebSocket('ws://ws.blockchain.info/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.send( JSON.stringify( {"op":"blocks_sub"} ) ); // subscribe to new blocks
};
 
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;
response.type = TYPE_TRANSACTION;
response.index = index++;
}
else if( response.op == "block" )
{
response.type = TYPE_BLOCK;
response.amount = Math.round( response.x.height / 10000 );
}

if( DEBUG )
console.log( response.op, response );

response.date = date;

};

You can find the source here:
https://gist.github.com/npedrini/6030317

Thank you for your response! I'm really a newbie, so I tried copying & pasting the code on your github into an html file, but it stuck loading. I also tried putting your code into mine, but that didn't work either. How should I implement your code?

Thanks again for your help, I really appreciate it.


Title: Re: Blockchain.info Websocket API
Post by: micaman on August 03, 2014, 10:50:58 PM
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");
initWebSocket();
}

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

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

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

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;
response.type = TYPE_TRANSACTION;
response.index = index++;
}
else if( response.op == "block" )
{
response.type = TYPE_BLOCK;
response.amount = Math.round( response.x.height / 10000 );
}

if( DEBUG )
console.log( response.op, response );

response.date = date;

writeToScreen('<span style="color: blue;">RESPONSE: ' + response.amount+'</span>');
};
}


function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
 
  // constants
var TYPE_TRANSACTION = "transaction";
var TYPE_TRADE = "trade";
var TYPE_BLOCK = "block";
var MINUTE = 1000*60;
var HOUR = MINUTE*60;
var MIN_MINUTES = 1;
var MAX_MINUTES = 10;
var DEBUG = true;
var activity = [];
var index = 0;

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

</script>

<h2>WebSocket Test</h2>

<div id="output"></div>
Well this is a 5 min on-top-of-the-knee script that will print every transaction received.
Check the API for all the available properties and try to change the code as you intend.
Good luck!  ;)


Title: Re: Blockchain.info Websocket API
Post by: Skull1234567 on August 05, 2014, 08:00:20 PM
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");
initWebSocket();
}

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

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

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

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;
response.type = TYPE_TRANSACTION;
response.index = index++;
}
else if( response.op == "block" )
{
response.type = TYPE_BLOCK;
response.amount = Math.round( response.x.height / 10000 );
}

if( DEBUG )
console.log( response.op, response );

response.date = date;

writeToScreen('<span style="color: blue;">RESPONSE: ' + response.amount+'</span>');
};
}


function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
 
  // constants
var TYPE_TRANSACTION = "transaction";
var TYPE_TRADE = "trade";
var TYPE_BLOCK = "block";
var MINUTE = 1000*60;
var HOUR = MINUTE*60;
var MIN_MINUTES = 1;
var MAX_MINUTES = 10;
var DEBUG = true;
var activity = [];
var index = 0;

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

</script>

<h2>WebSocket Test</h2>

<div id="output"></div>
Well this is a 5 min on-top-of-the-knee script that will print every transaction received.
Check the API for all the available properties and try to change the code as you intend.
Good luck!  ;)
Thank you so much! I really appreciate it!