jQuery
websocket

WebSocket のデータを受信するページ

WebSocket の データを受信するページです。

WebSocket の送信元は、BitFinex です。

次のように表示されます。
bitcoin_feb0201.png

ページ

<!DOCTYPE html>
<head lang="ja">
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="bitcoin.js"></script>
</head>
<body>
<div id="contents"></div>
<p />
Version: Feb/02/2018 PM 17:16<p />
</body>
bitcoin.js
// -----------------------------------------------------------------------
/*
    bitcoin.js

                    Feb/02/2018
*/
// -----------------------------------------------------------------------
var ws = new WebSocket('wss://api.bitfinex.com/ws/');

// -----------------------------------------------------------------------
jQuery (function ()
{
    var count = 0

    const params = {
            "event": "subscribe",
            "channel": "trades",
            "pair": "BTCUSD"
            }

    const json_str = JSON.stringify(params)

    ws.onopen = function()
        {
        ws.send (json_str)
        }

    ws.onmessage = function(msg)
        {
        const response = JSON.parse(msg.data)
        if (response[1] === 'te')
            {
            out_proc(response,count)
            count += 1
            }
        }
})

// -----------------------------------------------------------------------
// [4]:
function out_proc(response,count)
{
    var str_out = ""
    str_out += "<table>"
    str_out += "<tr><td>count</td><td>" + count + "</td></tr>"
    str_out += "<tr><td>CHANNEL_ID</td><td>" + response[0] + "</td></tr>"
    str_out += "<tr><td>te</td><td>" + response[1] + "</td></tr>"
    str_out += "<tr><td>SEQ</td><td>" + response[2] + "</td></tr>"
    str_out += "<tr><td>TIMESTAMP</td><td>" + response[3] + "</td></tr>"
    str_out += "<tr><td>PRICE</td><td>" + response[4] + "</td></tr>"
    str_out += "<tr><td>AMOUNT</td><td>" + response[5] + "</td></tr>"

    str_out += "</table>"

    jQuery("#contents").html (str_out)
}

// -----------------------------------------------------------------------