Bitcoin Forum
May 24, 2024, 08:59:15 AM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: Blockchain.info Websocket API  (Read 1814 times)
Skull1234567 (OP)
Newbie
*
Offline Offline

Activity: 5
Merit: 0


View Profile
July 31, 2014, 01:40:57 PM
 #1

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>

bitpop
Legendary
*
Offline Offline

Activity: 2912
Merit: 1060



View Profile WWW
August 02, 2014, 09:11:16 AM
 #2

Their cloud flare might be interfering causing the circuit to break. Why can't you just reload the page on an error?

Skull1234567 (OP)
Newbie
*
Offline Offline

Activity: 5
Merit: 0


View Profile
August 02, 2014, 02:23:18 PM
 #3

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).
micaman
Sr. Member
****
Offline Offline

Activity: 345
Merit: 500



View Profile WWW
August 02, 2014, 02:39:23 PM
 #4

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
Skull1234567 (OP)
Newbie
*
Offline Offline

Activity: 5
Merit: 0


View Profile
August 03, 2014, 07:46:17 PM
 #5

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.
micaman
Sr. Member
****
Offline Offline

Activity: 345
Merit: 500



View Profile WWW
August 03, 2014, 10:50:58 PM
 #6

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!  Wink
Skull1234567 (OP)
Newbie
*
Offline Offline

Activity: 5
Merit: 0


View Profile
August 05, 2014, 08:00:20 PM
 #7

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!  Wink
Thank you so much! I really appreciate it!
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!