Skip to content
Advertisement

Javascript websockets closing immediately after opening

connection = new WebSocket("ws://localhost:1050/join?username=test")

connection.onopen = function(){
   alert('Connection open!');
}


connection.onmessage = function(e){
   var server_message = e.data;
   alert(server_message);
}

connection.onclose = function() {
    alert("websocket closing")
}

The connection to the server is established and an alert is displayed for Connection open! However immediately afterwards the connection closes. The server does not call close and there seem to be no other errors in the console. This is happening in both chrome and firefox.

I looked at a bunch of different similar examples on the web but to no avail.

Advertisement

Answer

Fixed it!

All I had to do was block the handler from returning before the websocket connection closes

Advertisement