How to keep Websocket API session alive - websocket

I'm trying to keep subscribed to blockchain.info websocket api for new 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?
<!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>

I just tested this, and it seems to work:
<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 );
};
}
Largely taken from here: http://bl.ocks.org/npedrini/6030317

Related

ws.onmessage not called even though server is sending data

I'm using sockjs-0.3.4.
Before change page structure, it worked normally.
However after changing some stuff. abrubtly ws.onmessage function is beginning not to called.
I checked the connection with server by looking into devtools.
It looks like getting data from the server.
Please help me to know what's the point to check out.
enter image description here
var statusWatcher = {
curPage:"",
ws: null,
wsBaseUrl :null,
uid: null,
init : function(url ){
if(statusWatcher.ws != null) return;
console.log(statusWatcher.ws);
console.log("wsBaseUrl:"+url)
statusWatcher.wsBaseUrl = url;
var browserSupport = ("WebSocket" in window)? true: false;
if(browserSupport){
statusWatcher.start();
}else{
console.log("WebSocket is Not supported by your Web Browser!");
}
//log.eventHandler(1);
},
start : function(){
baseWsURL = statusWatcher.wsBaseUrl+"/statusCheck?&uid="+statusWatcher.uid;
console.log("web socket baseurl:"+baseWsURL);
try{
statusWatcher.ws = new WebSocket(baseWsURL);
} catch (e){
console.log(e);
}
statusWatcher.ws.onopen = function() {
console.log("web socket Opened! ");
};
statusWatcher.ws.onclose = function() {
console.log("web syslog socket Closed! ");
};
statusWatcher.ws = function(err) {
console.log("web syslog socket Error: " + err);
};
statusWatcher.ws.onmessage = function(evt) {
console.log("get message...");
//console.log("page:"+curPage);
var data = evt.data;
console.log(data);
var msg;
if(curPage =="main") return;
var e = JSON.parse(data);
if(e.status =="COMPLETE"){
$("#" + e.groupId).text("complete");
$("#" + e.groupId).removeClass('run error');
$("#" + e.groupId).addClass('complete');
statusWatcher.updateScoreState(e.groupId, "COMPLETE", e.topRplRate,e.topKwdRate);
}else if(e.status == "ERROR"){
$("#" + e.groupId).text("error");
$("#" + e.groupId).removeClass('run complete');
$("#" + e.groupId).addClass('error');
statusWatcher.updateScoreState(e.groupId, "ERROR");
}else{
$("#" + e.groupId).html("running("+e.progress+"/"+e.total+")");
$("#" + e.groupId).removeClass('error complete');
$("#" + e.groupId).addClass('run');
statusWatcher.updateScoreState(e.groupId, "RUNNING");
}
};
},
}
}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<script src="<c:url value="js/fileuploadMain/statusWatcher.js"/>"></script>
</head>
<body>
<!--header-->
<c:import url="/WEB-INF/jsp/fileupload/header.jsp" />
<!--contents-->
<div class="contents">
<div class="container" id="container">
</div>
</div>
<script>
$(document).ready(function() {
var nice = $("html").niceScroll(); // The document page (body)
$(".select-items").niceScroll({
zindex: "auto",boxzoom:false
});
$("#container").load("group.do");
calaendar.init();
var wsBaseUrl = "ws://"+document.location.host+"<c:out value="${pageContext.request.contextPath}"/>";
statusWatcher.init(wsBaseUrl);
});
</script>
</body>
</html>
statusWatcher.ws = function(err) {
console.log("web syslog socket Error: " + err);
};
I changed upper source code to the next.. Maybe I remove the function name mistakenly..
statusWatcher.ws.onerror = function(err) {
console.log("web syslog socket Error: " + err);
};

How to add live data to stacked bar chart

I have a stacked bar chart, which gains data from an api.
It works fine when loaded, and the data is displayed as it should be.
Now I wish to add new data to the chart every ten minutes, calling the same API as when loaded, the chart should refresh asynchronously and he new data and axis label need to be updated as new data is gained.
What I have done so far..
https://plnkr.co/edit/s2Os8UlpSbCWlkNP6wuA?p=preview
var ma = d3.line()
.x(function(d) { return x(parseDate(d.date)); })
.y(function(d) { return y(d.ma); });
If you use jquery, then you can send an AJAX request using the $.ajax function. Make sure you handle the response in the result's done() function, as success is deprecated.
Plain AJAX request example:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
JS:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Taken from here. If you mastered AJAX requests, then the next step is to write a poller, using setInterval. The first parameter should be a function which sends a request and the second should be the time between two execution in milliseconds (10000 in this case). Or you can use an existing poller. This is one I have implemented:
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function Poller(params) {
Initializable.call(this, params);
var that = this;
this.initialize("url", window.location.href);
this.initialize("interval", 5000);
this.initialize("type", "POST");
this.initialize("method", "POST");
this.initialize("data", {});
this.initialize("strict", true);
var defaultFunction = function() {};
this.initialize("done", defaultFunction);
this.initialize("fail", defaultFunction);
this.initialize("always", defaultFunction);
this.isRunning = function() {
return !!params.intervalID;
};
this.run = function() {
if (this.strict && (this.green === false)) {
return;
}
this.green = false;
$.ajax({
url: this.url,
method: this.method,
data: this.data
}).done(function(data, textStatus, jqXHR) {
that.green = true;
that.done(data, textStatus, jqXHR);
}).fail(function(jqXHR, textStatus, errorThrown) {
that.green = true;
that.fail(jqXHR, textStatus, errorThrown);
}).always(function(param1, param2, param3) {
that.green = true;
that.always(param1, param2, param3);
});
};
this.start = function() {
if (!params.intervalID) {
this.run();
params.intervalID = setInterval(this.run.bind(this), this.interval);
}
};
this.stop = function() {
if (!!params.intervalID) {
clearInterval(params.intervalID);
params.intervalID = undefined;
}
};
}

Browser does not render appended child node

I'm experimenting with web service to transmit new elements to document DOM.
So I'm preparing a XML on server side with necessary informations to do that job. My server side XML is as followed:
<Root>
<Command>Add
<Data><button id="PB" style="width:600px; height:100px;"/></Data>
</Command>
</Root>
This XML will be caught by following page.
You will see XML has a command id "Add", which should add the nodes below data to the page.
When code is running, the button will be created and shown properly in document DOM (see code function onMessage), but it will not be rendered.
The browser debugger tells me, the width and height of the button seems to be Null. When I edit the attributes in browser debugger, the button will be rendered after change. I get this behaviour on Chrome and IE.
I need a hint, what has to be changed to let it run.
<!DOCTYPE html>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8002/chat";
var output;
var websocket;
"use strict";
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.binaryType = "arraybuffer";
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");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
var parser, xmlDoc, NodeCommand, but;
parser = new DOMParser();
xmlDoc = parser.parseFromString(evt.data, "text/xml");
NodeCommand = xmlDoc.getElementsByTagName("Command");
switch (NodeCommand[0].textContent) {
case "Add":
output.appendChild(NodeCommand[0].childNodes[1].childNodes[0]);
break;
}
}
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>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Solved!
This can't be done in this (intuitive) way. Elements have to be created over document.

How to write in file using FileSystem API with IBM Worklight?

I am using HTML5's FileSystem API With Worklight to create cache files JSON format , I created to file without any problem , the problem is when I try to add some text to the created file , I used fileWriter but it doesn't write any thing .
this is the update function that I developed :
function update(fileName){
function onInitFs(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry .
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
}
window.requestFileSystem(window.PERSISTENT, 1024*1024, onInitFs, errorHandler);
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
document.querySelector('#example-list-fs-ul').innerHTML = 'Error: ' + msg;
}
}
This is the read function to show the content of the file and it return a blank String :
function read(fileName){
function onInitFs(fs) {
fs.root.getFile(fileName, {}, function(fileEntry) {
// Get a File object representing the file,
// then use FileReader to read its contents.
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
alert(this.result);
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
window.requestFileSystem(window.PERSISTENT, 1024*1024, onInitFs, errorHandler);
}
Any one have any Idea how to fix this and how to successfully write and read from the file ?
Thank You
I think it would be better to use some of the Worklight features designed specifically for the purpose you are trying to achieve, like:
Encrypted cache
JSONStore
Here is a sample that allows to create/edit/read/delete a simple text file.
Hope this helps.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>CordovaApp</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
<script type="text/javascript" charset="utf-8">
/**
* Function called when page has finished loading.
*/
function init(){
console.log("onDeviceReady");
}
onWLReady = function() {
// Wait for PhoneGap to load
document.addEventListener("deviceready", init, false);
}
function createFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false},
function(fileEntry) {
fileEntry.createWriter(
function(writer) {
writer.onwriteend = function(evt) {
log("File created...");
};
writer.onwritestart = function(evt){
log("onwritestart");
};
writer.onwrite = function(evt){
log("onwrite");
};
writer.onerror = function(evt){
log("onerror");
};
writer.write("File created at: " + new Date().toLocaleString());
},
fail);
}
, fail);
},
fail);
}
function editFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: false, exclusive: false},
function(fileEntry) {
fileEntry.createWriter(
function(writer) {
writer.onwriteend = function(evt) {
log("File edited");
};
writer.onwritestart = function(evt){
log("onwritestart");
};
writer.onwrite = function(evt){
log("onwrite");
};
writer.onerror = function(evt){
log("onerror");
};
writer.seek(writer.length);
writer.write("<br>File edited at: " + new Date().toLocaleString());
},
fail);
}
, fail);
},
fail);
}
function readFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getFile("readme.txt", {
create : false
},
function(fileEntry){
fileEntry.file(function(file) {
readDataUrl(file);
readAsText(file);
},
fail);
},
fail);
}, fail);
}
function readDataUrl(file){
var reader = new FileReader();
log("readDataUrl...");
reader.onloadstart = function(evt){
log("onloadstart: " + evt.target.result);
};
reader.onload = function(evt){
log("onload: " + evt.target.result);
};
reader.onloadend = function(evt){
log("onloadend: " + evt.target.result);
};
reader.onerror = function(evt){
log("onerror: " + evt.target.result);
};
reader.readAsDataURL(file);
reader.abort();
}
function readAsText(file){
var reader = new FileReader();
log("readAsText...");
reader.onloadstart = function(evt){
log("onloadstart: " + evt.target.result);
};
reader.onload = function(evt){
log("onload: " + evt.target.result);
};
reader.onloadend = function(evt){
log("onloadend: " + evt.target.result);
};
reader.onerror = function(evt){
log("onerror: " + evt.target.result);
};
reader.readAsText(file);
}
function deleteFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getFile("readme.txt", {
create : false
},
function(fileEntry){
fileEntry.remove(function() {log("File deleted.");
},
fail);
},
fail);
}, fail);
}
function fail(error){
var msg = error;
switch(error.code)
{
case FileError.NOT_FOUND_ERR:
msg = "File Not Found";
break;
case FileError.SECURITY_ERR:
msg = "Security Error";
break;
case FileError.ABORT_ERR:
msg = "Abort error";
break;
case FileError.NOT_READABLE_ERR:
msg = "Not Readable";
break;
case FileError.ENCODING_ERR:
msg = "Encoding Error";
break;
case FileError.NO_MODIFICATION_ALLOWED_ERR:
msg = "No Modification Allowed";
break;
case FileError.INVALID_STATE_ERR:
msg = "Invalid State";
break;
case FileError.SYNTAX_ERR:
msg = "Syntax Error";
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = "Invalid Modification Error";
break;
case FileError.QUOTA_EXCEEDED_ERR:
msg = "Quota Exceeded";
break;
case FileError.TYPE_MISMATCH_ERR:
msg = "Type Mismatch Error";
break;
case FileError.PATH_EXISTS_ERR:
msg = "Path Already Exists Error";
break;
}
log("fail: "+ msg);
}
function log(info){
document.getElementById('log').innerHTML += "<br>" + info;
}
function clearLog(info){
document.getElementById('log').innerHTML = "";
}
</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<div>
<button onclick="createFile();">Create File</button><br>
<button onclick="editFile();">Edit File</button><br>
<button onclick="readFile();">Read File</button><br>
<button onclick="deleteFile();">Delete File</button><br>
<button onclick="clearLog();">Clear Log</button><br>
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
<div><u><b>Log:</b></u></div>
<div id=log></div>
</body>
</html>
Note that the Javascript methods should better be in js/main.js instead of being defined in the html file. It was simply easier for me to provide a working sample as a single file.

Getting a getXMLHTTP is not defined error

Here is my javascript:
<script type="text/javascript">
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
//ERROR is right here
//UNCAUGHT REFERENCE ERROR: getXMLHTTP IS NOT DEFINED
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
It is being called from this:
<tr>
<td width="150">Country</td>
<td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option> </select></td>
</tr>
Just to be safe, this is my header, maybe I am doing this incorrectly?
<head>
<link rel="stylesheet" type="text/css" href="view/css/application.css" />
<script type="text/javascript" src="view/javascript/application.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
Another note, I am working off this example and he is using a mysql server, I am using ODBC to connect to an Access database. Would I not use xmlHTTP for this? I honestly don't know.
Your getXMLHTTP() should look like this :
<script type="text/javascript">
function getXMLHTTP() {
var x = false;
try {
x = new XMLHttpRequest();
}catch(e) {
try {
x = new ActiveXObject("Microsoft.XMLHTTP");
}catch(ex) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1) {
x = false;
}
}
}
return x;
}
function getState(countryId){
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req){
req.onreadystatechange = function(){
if (req.readyState == 4){
if (req.status == 200){
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>

Resources