Javascript websockets closing immediately after opening

Issue

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.

Solution

Fixed it!

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

Answered By – Aniruddh Chaturvedi

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.