12-websocket.agi 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /*---
  2. title: WebSocket echo
  3. group: Realtime
  4. summary: Upgrade the request and talk to the browser; frames come from the WebSocket window.
  5. setup: {"mocks":{"ws":{"refuse":false,"script":[{"afterMs":300,"text":"hello"},{"afterMs":400,"text":"how are you?"},{"afterMs":400,"text":"bye"}],"closeAfterMs":0}}}
  6. ---*/
  7. /*
  8. While this runs, open the WebSocket tab of the output and type frames
  9. yourself. The scripted frames end with "bye"; remove that frame in the
  10. WebSocket window to keep the socket open and chat with the script.
  11. */
  12. requirelib("websocket");
  13. if (!websocket.upgrade(30)) {
  14. sendResp("This was not a WebSocket request");
  15. exit();
  16. }
  17. websocket.send("Welcome, " + USERNAME + ". Say bye to leave.");
  18. while (true) {
  19. var msg = websocket.read(10000);
  20. if (msg === null) {
  21. websocket.send("Still there?");
  22. continue;
  23. }
  24. if (msg === false) {
  25. console.log("The browser closed the socket");
  26. break;
  27. }
  28. if (msg === "bye") {
  29. websocket.send("Goodbye!");
  30. break;
  31. }
  32. websocket.send("You said: " + msg.toUpperCase());
  33. }
  34. websocket.close();