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)

1  
!include once #1015699 // websocket
2  
3  
sbool webSocketOnMessage_withIdler_verbose;
4  
5  
static WebSocketClient webSocketOnMessage_withIdler(S url, final VF1<S> onMessage, double idleInterval) {
6  
  ret webSocketOnMessage_withIdler(url, onMessage, idleInterval, null);
7  
}
8  
9  
static WebSocketClient webSocketOnMessage_withIdler(S url, final VF1<S> onMessage, final double idleInterval, fS initialMessage, fO... args) ctex {
10  
  WebSocketClient client = new WebSocketClient(new URI(url)) {
11  
    java.util.Timer idler;
12  
    
13  
    public void onMessage(S s) {
14  
      if (!licensed()) ret with close(); // program exit
15  
      s = dropTrailingNullChars(s);
16  
      pcallF(onMessage, s);
17  
    }
18  
19  
    public void onOpen(ServerHandshake handshake) {
20  
      if (webSocketOnMessage_withIdler_verbose)
21  
        print("WebSocket connected.");
22  
      if (nempty(initialMessage))
23  
        send(format(initialMessage, args));
24  
      idler = doEvery(idleInterval, r {
25  
        if (webSocketOnMessage_withIdler_verbose)
26  
          print("websocket idling");
27  
        send("");
28  
      });
29  
    }
30  
    
31  
    public void onClose(int code, S reason, bool remote) {
32  
      cancelTimer(idler);
33  
      idler = null;
34  
    }
35  
    
36  
    public void onError(Exception e) { printStackTrace(e); }
37  
  };
38  
  
39  
  if (webSocketOnMessage_withIdler_verbose)
40  
    print("Connecting to WebSocket: " + url);
41  
  client.connect();
42  
  ret client;
43  
}

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: 304 / 348
Version history: 7 change(s)
Referenced in: [show references]