and_cesbo

Astra WebSocket test

May 31st, 2014
615
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.13 KB | None | 0 0
  1. -- https://cesbo.com/
  2.  
  3. local server_addr = "127.0.0.1"
  4. local server_port = 8000
  5.  
  6. local index_html =
  7. [[<!doctype html>
  8. <html>
  9. <head>
  10. <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
  11. <style>
  12. body {
  13.     font-family: monospace;
  14. }
  15. hr {
  16.     background-color: #0074c8;
  17.     height: 1px;
  18.     border: 0px;
  19. }
  20. #log {
  21.     border: 1px solid #0074c8;
  22.     font-family: monospace;
  23. }
  24. .buttons>input {
  25.     padding-right: 10px;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <h1>Astra WebSocket test</h1>
  31. <hr>
  32. <div class="buttons">
  33. <input type="button" value="Get Data" id="get_data" />
  34. </div>
  35. <textarea id="log" rows="24" cols="80"></textarea>
  36. </body>
  37. <script>
  38. $log = $('#log');
  39. $log.append("Astra WebSocket test is started...\n");
  40.  
  41. ws = new WebSocket("ws://" + location.host + "/api");
  42. ws.onopen = function(evt) { $log.append("Connection established\n"); };
  43. ws.onmessage = function(evt) { $log.append("Received:\n" + evt.data + "\n"); };
  44. ws.onclose = function(evt) { $log.append("Connection closed\n"); };
  45. ws.onerror = function(evt) {
  46.     $log.append("Error. See console for more information\n")
  47.     console.log("WebSocket Error: ", evt);
  48. };
  49.  
  50. $('#get_data').click(function(obj) { ws.send("GET DATA"); });
  51. </script>
  52. </html>
  53. ]]
  54.  
  55. function http_callback_root(server, client, request)
  56.     if not request then return nil end
  57.  
  58.     server:send(client, {
  59.         code = 200,
  60.         headers =
  61.         {
  62.             "Content-Type: text/html",
  63.             "Connection: close",
  64.         },
  65.         content = index_html,
  66.     })
  67. end
  68.  
  69. function http_callback_api(server, client, request)
  70.     if request == "GET DATA" then
  71.  
  72.         local f = io.open("COPYING")
  73.         local data = f:read("*all")
  74.         f:close()
  75.  
  76.         data = data:gsub("&", "&amp;")
  77.         data = data:gsub("<", "&lt;")
  78.         data = data:gsub(">", "&gt;")
  79.  
  80.         server:send(client, data)
  81.     end
  82. end
  83.  
  84. http_server({
  85.     addr = server_addr,
  86.     port = server_port,
  87.     name = "WebSocket test",
  88.     route = {
  89.         { "/",      http_callback_root },
  90.         { "/api",   http_websocket({ callback = http_callback_api }) },
  91.     }
  92. })
Advertisement
Add Comment
Please, Sign In to add comment