websocket.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. </head>
  6. <p>Flask Tornado</p>
  7. <p id="log"></p>
  8. <input id="say" type="text">
  9. <button id="send" type="button">Send!</button>
  10. <body>
  11. <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
  12. <script>
  13. $(document).ready(function () {
  14. if ("WebSocket" in window) {
  15. ws = new WebSocket("ws://" + document.domain + "/websocket/console");
  16. ws.onmessage = function (msg) {
  17. var message = JSON.parse(msg.data);
  18. $("p#log").html($("p#log").html() + "<p>" + msg.data + "</p>");
  19. };
  20. // Bind send button to websocket
  21. var $send = $("button#send")
  22. , $say = $("input#say");
  23. $send.live("click", function () {
  24. ws.send(JSON.stringify({'text': $say.val()}));
  25. });
  26. // Cleanly close websocket when unload window
  27. window.onbeforeunload = function () {
  28. ws.onclose = function () {
  29. }; // disable onclose handler first
  30. ws.close()
  31. };
  32. }
  33. ;
  34. });
  35. $(document).keyup(function (event) {
  36. if (event.keyCode == 13) {
  37. $("#send").trigger("click");
  38. }
  39. });
  40. </script>
  41. </body>
  42. </html>