github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/stream/web/html/main.js (about)

     1  var wsUri;
     2  var output;
     3  var count;
     4  var ws;
     5  
     6  window.addEventListener("load", function(evt) {
     7    wsUri  = "ws://" + window.location.host + "/stream/stream"
     8    output = document.getElementById("output");
     9    count  = document.getElementById("count");
    10  
    11    var print = function(message) {
    12      var d       = document.createElement("div");
    13      d.innerHTML = message;
    14      output.appendChild(d);
    15    };
    16  
    17    var parseCount = function(evt) {
    18      return JSON.parse(evt.data).count
    19    };
    20  
    21    var newSocket = function() {
    22      ws           = new WebSocket(wsUri);
    23      ws.onopen = function(evt) {
    24        print('<span style="color: green;">Connection Open</span>');
    25      }
    26      ws.onclose = function(evt) {
    27        print('<span style="color: red;">Connection Closed</span>');
    28        ws = null;
    29      }
    30      ws.onmessage = function(evt) {
    31        print('<span style="color: blue;">Update: </span>' + parseCount(evt));
    32      }
    33      ws.onerror = function(evt) {
    34        print('<span style="color: red;">Error: </span>' + parseCount(evt));
    35      }
    36    };
    37  
    38    newSocket()
    39  
    40    document.getElementById("send").onclick = function(evt) {
    41      if (!ws) {
    42        return false
    43      }
    44  
    45      var msg = { count: parseInt(count.value) }
    46  
    47      req = JSON.stringify(msg)
    48      print('<span style="color: blue;">Sent request: </span>' + req);
    49      ws.send(JSON.stringify(msg));
    50  
    51      return false;
    52    };
    53  
    54    document.getElementById("cancel").onclick = function(evt) {
    55      if (!ws) {
    56        return false;
    57      }
    58      ws.close();
    59      print('<span style="color: red;">Request Canceled</span>');
    60      return false;
    61    };
    62  
    63    document.getElementById("open").onclick = function(evt) {
    64      if (!ws) {
    65        newSocket()
    66      }
    67      return false;
    68    };
    69  })