Imported Upstream version 3.2
[platform/upstream/libwebsockets.git] / minimal-examples / ws-server / minimal-ws-server-threads / mount-origin / example.js
1 var head = 0, tail = 0, ring = new Array();
2
3 function get_appropriate_ws_url(extra_url)
4 {
5         var pcol;
6         var u = document.URL;
7
8         /*
9          * We open the websocket encrypted if this page came on an
10          * https:// url itself, otherwise unencrypted
11          */
12
13         if (u.substring(0, 5) === "https") {
14                 pcol = "wss://";
15                 u = u.substr(8);
16         } else {
17                 pcol = "ws://";
18                 if (u.substring(0, 4) === "http")
19                         u = u.substr(7);
20         }
21
22         u = u.split("/");
23
24         /* + "/xxx" bit is for IE10 workaround */
25
26         return pcol + u[0] + "/" + extra_url;
27 }
28
29 function new_ws(urlpath, protocol)
30 {
31         if (typeof MozWebSocket != "undefined")
32                 return new MozWebSocket(urlpath, protocol);
33
34         return new WebSocket(urlpath, protocol);
35 }
36
37 document.addEventListener("DOMContentLoaded", function() {
38
39         ws = new_ws(get_appropriate_ws_url(""), "lws-minimal");
40         try {
41                 ws.onopen = function() {
42                         document.getElementById("r").disabled = 0;
43                 };
44         
45                 ws.onmessage =function got_packet(msg) {
46                         var n, s = "";
47         
48                         ring[head] = msg.data + "\n";
49                         head = (head + 1) % 50;
50                         if (tail === head)
51                                 tail = (tail + 1) % 50;
52         
53                         n = tail;
54                         do {
55                                 s = s + ring[n];
56                                 n = (n + 1) % 50;
57                         } while (n !== head);
58         
59                         document.getElementById("r").value = s; 
60                         document.getElementById("r").scrollTop =
61                                 document.getElementById("r").scrollHeight;
62                 };
63         
64                 ws.onclose = function(){
65                         document.getElementById("r").disabled = 1;
66                 };
67         } catch(exception) {
68                 alert("<p>Error " + exception);  
69         }
70
71 }, false);