main.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // This is necessary if you want to take advantage of setTimeout/clearTimeout, setInterval/clearInterval, setImmediate/clearImmediate
  2. require('AtomicEventLoop');
  3. var num_times_to_connect = 5;
  4. // Get the web subsystem
  5. var web = Atomic.getWeb();
  6. // Make the ws:// request
  7. var ws = web.makeWebSocket("ws://echo.websocket.org");
  8. // Listen for when the websocket is open
  9. ws.subscribeToEvent("open", function() {
  10. print("WebSocket Opened");
  11. ws.send(JSON.stringify({
  12. "test_key": "test_value",
  13. "life_the_universe_and_everything": 42
  14. }, undefined, 2));
  15. });
  16. // Listen for messages
  17. ws.subscribeToEvent("message", function (event) {
  18. print("WebSocket Message: " + event.data);
  19. // We would normally keep the WebSocket open for a long time, but
  20. // here we are demonstrating how to use ws.openAgain() below, so
  21. // we'll close the WebSocket after 5 seconds of getting the message.
  22. setTimeout(function() {
  23. ws.close();
  24. }, 2000);
  25. });
  26. // Listen for when the websocket is closed
  27. ws.subscribeToEvent("close", function() {
  28. print("WebSocket Closed");
  29. if (num_times_to_connect) {
  30. num_times_to_connect--;
  31. // Open the websocket again after 5 more seconds.
  32. setTimeout(function() {
  33. ws.openAgain();
  34. }, 2000);
  35. } else {
  36. Atomic.getEngine().exit();
  37. }
  38. });