Is there anyway to improve this javascript function with try and catch

After 2 days of try and error I finally get the result I want. But I think this is the dumbest way to check Websocket connection.

The internet suggestions that I should use try and catch. But never play with it before I have no idea where to begin with.


var ws = "ws://75.98.171.173:8008"
  , ww = "ws://75.98.171.173:8080";

var x = new WebSocket(ws);
x.onopen = function() {
	xx(ws);
};

var y = new WebSocket(ww);
y.onopen = function() {
	xx(ww);
};

var xx  = function(w) {
	yy(y);
};

var yy = function(i) {
	console.log(i);
};

The reason I check WebSocket connection is that some places have blocked a certain port connection such as workplace blah blah blah (port 80 is being use by PHP –> Apache to be exact). With port availability check up, people may be able to access to my app from anywhere.

PS: some place does not block any port and I want I use only one port at the time.
Thank you,

Hi,

When you say “check WebSocket connection”, do you want to check if the browser supports websockets or do you want to check if the connection is accepted and established by the server?

As for try and catch, you could do something like:

function openWebsocket(url){
    try {
        socket = new WebSocket(url);
        socket.onopen = function(){
            console.log('Socket is now open.');
        };
        socket.onerror = function (error) {
            console.error('There was an un-identified Web Socket error');
        };
        socket.onmessage = function (message) {
            console.info("Message: %o", message.data);
        };
    } catch (e) {
        console.error('Sorry, the web socket at "%s" is un-available', url);
    }
}

openWebsocket("ws://75.98.171.173:8008");
openWebsocket("ws://75.98.171.173:8080");

Hi, Pullo

Thank you for your help. It works.

I want to check if the connection is accepted and established by the server. As I said some places have set firewall or router to block certain internet port connection.