websocket.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. WebSocket Test Script
  3. This is a special test script and should not be mixed in with normal
  4. AGI module test scripts. Please test this seperately
  5. Author: tobychui
  6. */
  7. function setup(){
  8. //Require the WebSocket Library
  9. var succ = requirelib("websocket");
  10. if (!succ){
  11. console.log("WebSocket Open Failed");
  12. return false
  13. }
  14. //Upgrade the current connection to WebSocket, set timeout to 30 seconds
  15. //Timeout value: if after 30 seconds nothing has been send / received, the websocket will be closed
  16. //set this value to 0 to display auto socket closing
  17. succ = websocket.upgrade(30);
  18. if (!succ){
  19. console.log("WebSocket Upgrade Failed");
  20. return false
  21. }
  22. console.log("WebSocket Opened!")
  23. return true;
  24. }
  25. function waitForStart(){
  26. websocket.send("Send 'start' to start websocket.send test");
  27. var recv = "";
  28. for (var i = 0; i < 10; i++){
  29. //Read the websocket input from Client (Web UI)
  30. recv = websocket.read();
  31. if (recv == null){
  32. console.log("Read Failed!")
  33. return
  34. }
  35. if (recv != "start"){
  36. websocket.send(recv + " reveived. Type 'start' to start testing. (Retry count: " + i + "/10)");
  37. }else{
  38. websocket.send("'start' command received. Starting test");
  39. break;
  40. }
  41. }
  42. }
  43. function loop(i){
  44. //If the process reach here, that means the WebSocket connection has been opened
  45. console.log("Sending: Hello World: " + i);
  46. //Sebd Hello World {i} to Client (Web UI)
  47. websocket.send("Hello World: " + i);
  48. //Wait for 1 second before next send
  49. delay(1000);
  50. }
  51. function closing(){
  52. //Try to close the WebSocket connection
  53. websocket.close();
  54. }
  55. //Start executing the script
  56. if (setup()){
  57. waitForStart();
  58. for (var i = 0; i < 10; i++){
  59. loop(i);
  60. }
  61. closing();
  62. }else{
  63. console.log("WebSocket Setup Failed.")
  64. }