<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<p>Flask Tornado</p>
<p id="log"></p>
<input id="say" type="text">
<button id="send" type="button">Send!</button>
<body>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
    $(document).ready(function () {

        if ("WebSocket" in window) {
            ws = new WebSocket("ws://" + document.domain + "/websocket/console");
            ws.onmessage = function (msg) {
                var message = JSON.parse(msg.data);
                $("p#log").html($("p#log").html() + "<p>" + msg.data + "</p>");
            };

            // Bind send button to websocket
            var $send = $("button#send")
                    , $say = $("input#say");

            $send.live("click", function () {
                ws.send(JSON.stringify({'text': $say.val()}));
            });

            // Cleanly close websocket when unload window
            window.onbeforeunload = function () {
                ws.onclose = function () {
                }; // disable onclose handler first
                ws.close()
            };
        }
        ;
    });

    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $("#send").trigger("click");
        }
    });
</script>
</body>
</html>
