5
votes

I'm writing browser extensions for Firefox, Chrome and Safari. When attempting to connect to a WebSocket server using the Safari Extension where there is NO server listening on a particular port, my Safari extension doesn't throw an exception, nor does it call onerror. Instead, the Safari extension's onclose handler is being called. I'm also seeing this message in the console:

[Error] WebSocket network error: The operation couldn’t be completed. Connection refused (global.html, line 0)

On Firefox and Chrome, it seems to handle it properly AFAIK and calls onerror.

I'm just doing something like this:

var socket = new WebSocket('ws://127.0.0.1:'+inPort, inHandlerName);
socket.binaryType = "arraybuffer";

then declare handlers for onopen, onclose, onerror, and onmessage. inPort is 9000 and inHandlerName is a string like "global-handler". I put exception handlers in each of the WebSocket handlers and also the function that has the code that creates the WebSocket, but I am not seeing any exceptions caught.

Is this a known problem? Is there a way to find out if the connection failed?

Edit: This happens on a simple web page in Safari as well:

        var theSocket = new WebSocket('ws://127.0.0.1:9000', 'global-message');

        theSocket.onopen = function()
        {
            console.log("onopen");
        };
        theSocket.onerror = function()
        {
            console.log("onerror");
        };
        theSocket.onmessage = function()
        {
            console.log("onmessage");
        };
        theSocket.onclose = function()
        {
            console.log("onclose");
        };
1
The reason why I need to know the difference between a close and an error is so that I can try a different port number in case the server was unable to bind to a specific port. If it was a close, it may have been that the server crashed, but was able to bind originally to the port, so the client may want to try on that same port again.Elliott

1 Answers

8
votes

This doesn't seem like the way it should work, but in the onclose message, I'm getting an event parameter like this:

theSocket.onclose = function(event)

and the event contains a field called code. When I can't connect to a server, the code value is 1006. I've currently fixed it so that it checks to see if it's running in Safari and then check:

if(event.code == 1006)

and if so, I will do the same processing I do in the error cases for Firefox and Chrome.