Skip to content

Instantly share code, notes, and snippets.

Created September 14, 2015 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/057a874df38cfbef507e to your computer and use it in GitHub Desktop.
Save anonymous/057a874df38cfbef507e to your computer and use it in GitHub Desktop.
ibm bluemix websocket test
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
//グーグルチャートの読み込み
google.load("visualization", "1", {packages:["corechart"]});
//jQueryスタート
$(function() {
//グラフ用データ
var chart;
var dataArray = [['Date', 'distance']];
//初期化関数
/*------------------------------------------------------------------------*/
function init(){
//グラフ初期化
chartInit();
}
//グラフ初期化
/*------------------------------------------------------------------------*/
function chartInit(){
//0でデーターを埋めておく
var i;
for(i=1;i<100;i++){
dataArray[i] = ["",0];
}
//グラフの作成
google.setOnLoadCallback(drawChart);
chart = new google.visualization.LineChart(document.getElementById('chart'));
}
//グラフの描画
/*------------------------------------------------------------------------*/
function drawChart() {
//配列からグラフを描画(初期化)
var data = google.visualization.arrayToDataTable( dataArray );
chart.draw(data);
//WebScoketの開始
webSocketInit();
}
//WebScoketの開始
/*------------------------------------------------------------------------*/
function webSocketInit(){
//URL指定
var wsUri = "ws://testap2.mybluemix.net/ws/sensor";
websocket = new WebSocket(wsUri);
//ソケットオープン
websocket.onopen = function(ev) {
$('#message').append("<p>Connected!</p>");
};
//メッセージ取得イベント
websocket.onmessage = function(ev) {
//メッセージを解析
var msg = JSON.parse(ev.data);
var date = Math.floor( $.now() / 1000 );
var distance = msg.distance;
$('#message').prepend( "<p>date:" + date + " distance:" + distance + "</p>" );
//グラフの配列データーに追加
dataArray.push([date , distance ]);
//グラフの配列データーの頭を削除
if( dataArray.length >= 100 ){
dataArray.splice( 1 , 1 );
}
//グラフへ反映
var data = google.visualization.arrayToDataTable( dataArray );
chart.draw(data);
};
//エラー処理
websocket.onerror = function(ev){$('#message').append("<div class=\"system_error\">Error Occurred - "+ev.data+"</div>");};
websocket.onclose = function(ev){$('#message').append("<div class=\"system_msg\">Connection Closed</div>");};
}
init();
});
</script>
<!--<link rel="stylesheet" href="reset.css" type="text/css" media="all">-->
<!--<link rel="stylesheet" href="index.css" type="text/css" media="all">-->
</head>
<body>
<h1>WebScoketグラフ</h1>
<div id="chart"></div>
<h2>WebSocketログ</h2>
<div id="message"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment