Javascript-forum
Java Script Websocket closes immediately after creation - Druckversion

+- Javascript-forum (https://javascript-forum.de)
+-- Forum: Entwicklung (https://javascript-forum.de/forumdisplay.php?fid=4)
+--- Forum: Javascript (https://javascript-forum.de/forumdisplay.php?fid=6)
+--- Thema: Java Script Websocket closes immediately after creation (/showthread.php?tid=1774)



Java Script Websocket closes immediately after creation - DavidB - 08.11.2022

Hey, 
I'm relatively new to the java script world,
I'm trying to send a message with a java script websocket.

Code:
var ws = new WebSocket("ws://".concat(host_ip.concat(":8765")));

document.addEventListener('keyup', (e) => {
        //If I create the websocket here it works
        //var ws = new WebSocket("ws://".concat(host_ip.concat(":8765")));
        ws.onopen = function(event){
            console.log(ws);
            ws.send("TestMessage");
        }
});
If I create the websocket outside the addEventListener method the connection is closed (ready state 3)
when I try to send "TestMessage" by releasing the 'keyup' key.

If I create the websocket within the addEventListener method everything works just fine.
However when I'm sending too many messages successively the connection stops.

Has someone an idea why it does not work in the first case? Is this maybe some js variable out of scope error?



RE: Java Script Websocket closes immediately after creation - rzscout - 11.11.2022

Hi DavidB,
thank for your thread. The problem is that your thread is written in English. This forum is in German. Perhaps you could post your contribution again in German.