Links2004 / arduinoWebSockets

arduinoWebSockets
GNU Lesser General Public License v2.1
1.88k stars 556 forks source link

Initial delay of 10s #770

Closed s0170071 closed 2 years ago

s0170071 commented 2 years ago

Whenever I call a website, the initial template loads immediately, the websocket connection kicks in about 10 seconds later, but then it works okay. It should be much faster. Any hint on what causes this delay ? The browser claims it initiated the connection but there is no answer.

My code is:

For the website

<!DOCTYPE html>
<html>
  <head>
    <title>EHZ Web Server</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body onload ="initWebSocket()" bgcolor="000000" >
    ...
  <script>

  function init() { 
    Socket = new WebSocket('ws://' + window.location.hostname + ':81/'); 
    Socket.onmessage = function(event) { processReceivedCommand(event); }; 
  } 

  function processReceivedCommand(event) { 
    var obj = JSON.parse(event.data); 
    var Power = obj.ehz;
    document.getElementById('ehz').innerHTML = Power;
    if (Power >0 ) {
        document.getElementById('ehzstyle').style.color="red"; 
    } else {
        document.getElementById('ehzstyle').style.color="green"; 
    }

    document.getElementById('erzeugung').innerHTML = obj.erzeugung;
    document.getElementById('hausverbrauch').innerHTML = obj.hausverbrauch;
    if (obj.SMS >0 ) {
       document.getElementById('SMS').innerHTML = obj.SMS;
    } else {
       document.getElementById('SMS').innerHTML = "&nbsp;";
    }
    console.log('received json ' + event);  
    } 
  window.onload = function(event) {init();}
</script>
</body>
</html>

globals:

    WebSocketsServer webSocket = WebSocketsServer(81);
    DNSServer dnsServer;
   WebServer server(80);

setup():

         server.on("/EHZ", HTTP_GET,[]() { handleEHZ(); });  
         webSocket.begin();  
         webSocket.onEvent(webSocketEvent);  
         MDNS.addService("http", "tcp", 80);
         MDNS.addService("ws", "tcp", 81);

I do not use the callback function. When I send data, I use

webSocket.broadcastTXT( s.c_str());

to send a JSON string.

s0170071 commented 2 years ago

solved: I did not loop() fast enough. Apparently it takes about 10 loopos for the initial response.