Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

43
LINES

< > BotCompany Repo | #1015695 // webSocketOnMessage_withIdler - open a WebSocket and react to messages. Closed on program exit. Does not block

JavaX fragment (include)

!include once #1015699 // websocket

sbool webSocketOnMessage_withIdler_verbose;

static WebSocketClient webSocketOnMessage_withIdler(S url, final VF1<S> onMessage, double idleInterval) {
  ret webSocketOnMessage_withIdler(url, onMessage, idleInterval, null);
}

static WebSocketClient webSocketOnMessage_withIdler(S url, final VF1<S> onMessage, final double idleInterval, fS initialMessage, fO... args) ctex {
  WebSocketClient client = new WebSocketClient(new URI(url)) {
    java.util.Timer idler;
    
    public void onMessage(S s) {
      if (!licensed()) ret with close(); // program exit
      s = dropTrailingNullChars(s);
      pcallF(onMessage, s);
    }

    public void onOpen(ServerHandshake handshake) {
      if (webSocketOnMessage_withIdler_verbose)
        print("WebSocket connected.");
      if (nempty(initialMessage))
        send(format(initialMessage, args));
      idler = doEvery(idleInterval, r {
        if (webSocketOnMessage_withIdler_verbose)
          print("websocket idling");
        send("");
      });
    }
    
    public void onClose(int code, S reason, bool remote) {
      cancelTimer(idler);
      idler = null;
    }
    
    public void onError(Exception e) { printStackTrace(e); }
  };
  
  if (webSocketOnMessage_withIdler_verbose)
    print("Connecting to WebSocket: " + url);
  client.connect();
  ret client;
}

Author comment

Began life as a copy of #1015083

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1015695
Snippet name: webSocketOnMessage_withIdler - open a WebSocket and react to messages. Closed on program exit. Does not block
Eternal ID of this version: #1015695/8
Text MD5: e5873da2853c8ad93c4556ff2d47ed33
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-07-30 15:18:58
Source code size: 1402 bytes / 43 lines
Pitched / IR pitched: No / No
Views / Downloads: 301 / 344
Version history: 7 change(s)
Referenced in: [show references]