0

Websocket only sends a message if onopen was invoked and no where else. The server just sends back the message with Hello added.

Client side:

    <!DOCTYPE html>
<html>
    <body>
        <button onclick="transmit()">send</button>
        <h3 id="text"></h3>
    </body>
    <script>
            const url = "ws://localhost:8765"
            const ws = new WebSocket(url)
            var i = 0;

            ws.onopen = function (event) {
                ws.send('On');
            }

            ws.onmessage = function (event){
                ws.send("This will cause a feedback loop but idc at this point");
                var text = document.getElementById("text");
                text.innerHTML = evt.data;
            }

            ws.send("pain");
                
    </script>
</html> 

I am probably doing something stupid lol.

1 Answer 1

1

Websockets closes automatically upon no activity, afterwards all send is ignored. To prevent it from closing here is an approach.

ws.onopen = function (event) {
  ws.send('On');

  return false; // keeps the socket open.
}

//or 
ws.onmessage = function (event){
   ws.send("This will cause a feedback loop but idc at this point");
   var text = document.getElementById("text");
   text.innerHTML = evt.data;

   return false; // keeps the socket open.
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the reply! It still doesn't send after onopen tho.
you can return false on that too actually, just to keep it open. See edits.
It is still not working for some reason

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.