Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Javascript sending only one message over websocket in browser

I have a websocketserver running on a ESP32 which works perfect.

My problem is that if I send a message to the server over a website the socketserver on the ESP32 executes the .send(message) only the first time and is not sending anymore any message.

If I send a message from the developertools/console in chrome it works every time.

At this point I suppose my problem seems not to be on the server-side but on the client-side.

This is my html/javascript-code running inside chrome:


    <!DOCTYPE html>

<head>
    <title>WH_Quiz</title>
    <style>
        body {
            background: url(Images/SET_1/A1_INTRO.png) no-repeat center center fixed;
            -webkit-background-size: cover;
            background-size: cover;
        }
    </style>
    
</head>

<body>


    <script>
        // clear localStorage
        window.localStorage.clear();

        // open websocket
        var url = "ws://192.168.4.1:1337";
        websocket = new WebSocket(url);
        websocket.onopen = function (event) {
            console.log('websocket is open');
            websocket.send("L");
        };
        
        
        // Keep track of clicked keys
        var isKeyPressed = {
            'a': false, // ASCII code for 'a'
            'b': false, // ASCII code for 'b'
            // ... Other keys to check for custom key combinations
        };

        document.onkeydown = (keyDownEvent) => {

            // Prevent default key actions, if desired
            keyDownEvent.preventDefault();

            // Track down key click
            isKeyPressed[keyDownEvent.key] = true;

            // Check described custom shortcut
            if (isKeyPressed['a']) { //for example we want to check if a is clicked
                //do something 
                console.log('a has been pressed');

                websocket.onopen = function (event) {
                    console.log('a has been pressed and wesocket is open');
                    window.location.href = '1_1.html'; // öffne Fragenkatalog 1
                    websocket.send("4G");
                };

            };
            // Check described custom shortcut
             if (isKeyPressed['b']) { //for example we want to check if b is clicked
                //do something 
                console.log('b has been pressed');
                                
                websocket.onopen = function (event) {
                    window.location.href = '2_1.html'; // öffne Fragenkatalog 2
                    websocket.send("4R");
                };
            };
        };
    </script>
</body>

</html>

In my console logs I can see that it enters the "isKeyPressed" if-statement but it is not executing the "websocket.onopen = function (event)".

What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

websocket.onopen is only triggered the first time the socket is open. Since it's already open at this point, you should be able to just directly call the send function.

In other words:

if (isKeyPressed['b']) { //for example we want to check if b is clicked
  //do something 
  console.log('b has been pressed');
                                
  websocket.onopen = function (event) {
    window.location.href = '2_1.html'; // öffne Fragenkatalog 2
    websocket.send("4R");
  };
};

becomes:

if (isKeyPressed['b']) { //for example we want to check if b is clicked
  //do something 
  console.log('b has been pressed');          
  window.location.href = '2_1.html'; // öffne Fragenkatalog 2
  websocket.send("4R");          
};
about 4 years ago · Juan Pablo Isaza Relatório

0

I dont know much about websockets but it looks like the onopen() function is like the onready() function in discord.js. It only runs when the script is started/ the websocket is opened.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda