| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- // This is necessary if you want to take advantage of setTimeout/clearTimeout, setInterval/clearInterval, setImmediate/clearImmediate
- require('AtomicEventLoop');
- var num_times_to_connect = 5;
- // Get the web subsystem
- var web = Atomic.getWeb();
- // Make the ws:// request
- var ws = web.makeWebSocket("ws://echo.websocket.org");
- // Listen for when the websocket is open
- ws.subscribeToEvent("open", function() {
- print("WebSocket Opened");
- ws.send(JSON.stringify({
- "test_key": "test_value",
- "life_the_universe_and_everything": 42
- }, undefined, 2));
- });
- // Listen for messages
- ws.subscribeToEvent("message", function (event) {
- print("WebSocket Message: " + event.data);
- // We would normally keep the WebSocket open for a long time, but
- // here we are demonstrating how to use ws.openAgain() below, so
- // we'll close the WebSocket after 5 seconds of getting the message.
- setTimeout(function() {
- ws.close();
- }, 2000);
- });
- // Listen for when the websocket is closed
- ws.subscribeToEvent("close", function() {
- print("WebSocket Closed");
- if (num_times_to_connect) {
- num_times_to_connect--;
- // Open the websocket again after 5 more seconds.
- setTimeout(function() {
- ws.openAgain();
- }, 2000);
- } else {
- Atomic.getEngine().exit();
- }
- });
|