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

120
LINES

< > BotCompany Repo | #1032264 // HInitWebSocket

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (24120L/146K).

1  
// defines:
2  
// variable ws (the websocket)
3  
// variable wsReady (boolean)
4  
// variable wsVerbose (boolean)
5  
// wsSend(msg) (send a message when websocket is ready)
6  
// wsOnMessage(function(event) {...}) (react to messages)
7  
// wsOnOpen(function() {}) (react to opening of websocket)
8  
sclass HInitWebSocket {
9  
  S wsVar = "ws"; // TODO: not used everywhere
10  
  S readyMsg = "WebSocket ready!";
11  
  bool handleEvals = true; // automatically handle {"eval":"jsCode();"}
12  
  bool wsVerbose = true; // now defaults to true (it's just so useful)
13  
  bool autoOpen = true; // open websocket immediately - otherwise call ws.open() later
14  
  
15  
  new MapSO params;
16  
  
17  
  // appended to URL it it's not the first connect
18  
  S reconnectParams = "reconnect=1";
19  
  
20  
  *() {}
21  
  *(IWebRequest req) {
22  
    if (req != null && eq(req.get("wsVerbose"), "1"))
23  
      set wsVerbose;
24  
  }
25  
  
26  
  public S headStuff aka get aka toString() {
27  
    ret hreconnectingWebSockets() + hscript(js());
28  
  }
29  
  
30  
  LS dependencies() {
31  
    ret ll(hjssnippet(hreconnectingWebSockets_snippetID(), "data-comment" := "ReconnectingWebSocket"));
32  
  }
33  
  
34  
  S js() {
35  
    ret jsDollarVars([[
36  
      var wsReady = false;
37  
      var wsInitialMsgs = [];
38  
      var wsMsgListeners = [];
39  
      var wsOpenListeners = [];
40  
      var wsWillReconnectListeners = [];
41  
      var wsVerbose = $wsVerbose;
42  
      var wsConnectionCount = 0;
43  
      var wsAugmentURL = function(url) { return url; };
44  
      var wsURL = ((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host
45  
        + window.location.pathname + window.location.search;
46  
      if ($params != "")
47  
        wsURL += (wsURL.match(/\?/) ? "&" : "?") + $params;
48  
        
49  
      var $wsVar = new ReconnectingWebSocket(wsURL, null, $options);
50  
      
51  
      $wsVar.onopen = function(event) {
52  
        wsReady = true;
53  
        console.log($readyMsg + " " + ws.url);
54  
        
55  
        if (++wsConnectionCount == 1)
56  
          if ($reconnectParams != "") {
57  
            wsURL += (wsURL.match(/\?/) ? "&" : "?") + $reconnectParams;
58  
            ws.url = wsAugmentURL(wsURL);
59  
          }
60  
61  
        wsOpenListeners.forEach(function(f) { f(); });
62  
63  
        ws.onmessage = function(event) {
64  
          if (wsVerbose) console.log("Got msg: " + event.data.substring(0, 200));
65  
          wsMsgListeners.forEach(function(listener) {
66  
            listener(event);
67  
          });
68  
        };
69  
        
70  
        ws.onclose = function(event) {
71  
          if (wsVerbose) console.log("WebSocket closed");
72  
          wsReady = false;
73  
        };
74  
75  
        wsInitialMsgs.forEach(function(msg) {
76  
          if (wsVerbose) console.log("Sending initial msg: " + msg);
77  
          ws.send(msg);
78  
        });
79  
        wsInitialMsgs = [];
80  
        if (wsVerbose) console.log("Cleared initial msgs");
81  
      };
82  
      
83  
      // send it now if ws is open already or when ws was opened
84  
      function wsSend(msg) {
85  
        if (wsReady) {
86  
          if (wsVerbose) console.log("Sending msg: " + msg);
87  
          ws.send(msg); // TODO: wsReady = false on failed send?
88  
          return;
89  
        } else {
90  
          if (wsVerbose) console.log("Scheduling msg: " + msg);
91  
          wsInitialMsgs.push(msg);
92  
        }
93  
      }
94  
      
95  
      function wsOnOpen(f) {
96  
        wsOpenListeners.push(f);      
97  
      }
98  
      
99  
      function wsOnMessage(f) {
100  
        wsMsgListeners.push(f);      
101  
      }
102  
      
103  
      function wsSetAugmentURL(f) {
104  
        wsAugmentURL = f;
105  
        if (ws) ws.url = wsAugmentURL(wsURL);
106  
      }
107  
      
108  
      ]], wsVar := JS(wsVar), +wsVerbose, +readyMsg,
109  
        params := makePostData(params),
110  
        reconnectParams := unnull(reconnectParams),
111  
        +options())
112  
    + (!handleEvals ? "" : "wsOnMessage(" + js_evalOnWebSocketMessage() + ");\n");
113  
  }
114  
  
115  
  Map options() {
116  
    ret litorderedmap(
117  
      automaticOpen := autoOpen ? null : false
118  
    );
119  
  }
120  
}

Author comment

Began life as a copy of #1029959

download  show line numbers  debug dex  old transpilations   

Travelled to 5 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj, pyentgdyhuwx

No comments. add comment

Snippet ID: #1032264
Snippet name: HInitWebSocket
Eternal ID of this version: #1032264/47
Text MD5: 3ccfa51ad722d2e7e6df4af1ff0bd7dc
Transpilation MD5: 2443435c0821b15196f636635c9f6990
Author: stefan
Category: javax / html
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-11-16 22:28:15
Source code size: 3916 bytes / 120 lines
Pitched / IR pitched: No / No
Views / Downloads: 244 / 559
Version history: 46 change(s)
Referenced in: [show references]