main.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // Make the ws:// request
  5. var ws = new Atomic.WebSocket("ws://echo.websocket.org");
  6. // Listen for when the websocket is open
  7. ws.subscribeToEvent("open", function() {
  8. console.log("WebSocket Opened");
  9. ws.send(JSON.stringify({
  10. "test_key": "test_value",
  11. "life_the_universe_and_everything": 42
  12. }, undefined, 2));
  13. });
  14. // Listen for messages
  15. ws.subscribeToEvent("message", function (event) {
  16. console.log("WebSocket Message: " + event.message.readString());
  17. // We would normally keep the WebSocket open for a long time, but
  18. // here we are demonstrating how to use ws.openAgain() below, so
  19. // we'll close the WebSocket after a few seconds of getting the message.
  20. setTimeout(function() {
  21. ws.close();
  22. }, 2000);
  23. });
  24. // Listen for when the websocket is closed
  25. ws.subscribeToEvent("close", function() {
  26. console.log("WebSocket Closed");
  27. if (num_times_to_connect) {
  28. num_times_to_connect--;
  29. // Open the websocket again after a few more seconds.
  30. setTimeout(function() {
  31. ws.openAgain();
  32. }, 2000);
  33. } else {
  34. console.log("Done!");
  35. }
  36. });