getting the reason why websockets closed with close code 1006

JavascriptWebsocket

Javascript Problem Overview


I would like to get the reason websockets closed, so I can show the right message to the user.

I have

sok.onerror=function (evt) 
     {//since there is an error, sockets will close so...
       sok.onclose=function(e){
           console.log("WebSocket Error: " , e);}

The code is always 1006 and the reason is always " ". But I want to tell different closing reasons apart.

For example the comand line gives an error reason : "you cannot delete that, because database wont let you". But on Chrome's console, the reason is still " ".

Any other way to tell different closing reasons apart?

Javascript Solutions


Solution 1 - Javascript

Close Code 1006 is a special code that means the connection was closed abnormally (locally) by the browser implementation.

If your browser client reports close code 1006, then you should be looking at the websocket.onerror(evt) event for details.

However, Chrome will rarely report any close code 1006 reasons to the Javascript side. This is likely due to client security rules in the WebSocket spec to prevent abusing WebSocket. (such as using it to scan for open ports on a destination server, or for generating lots of connections for a denial-of-service attack).

Note that Chrome will often report a close code 1006 if there is an error during the HTTP Upgrade to Websocket (this is the step before a WebSocket is technically "connected"). For reasons such as bad authentication or authorization, or bad protocol use (such as requesting a subprotocol, but the server itself doesn't support that same subprotocol), or even an attempt at talking to a server location that isn't a WebSocket (such as attempting to connect to ws://images.google.com/)

Fundamentally, if you see a close code 1006, you have a very low level error with WebSocket itself (similar to "Unable to Open File" or "Socket Error"), not really meant for the user, as it points to a low level issue with your code and implementation. Fix your low level issues, and then when you are connected, you can then include more reasonable error codes. You can accomplish this in terms of scope or severity in your project. Example: info and warning level are part of your project's specific protocol, and don't cause the connection to terminate. With severe or fatal messages reporting also using your project's protocol to convey as much detail as you want, and then closing the connection using the limited abilities of the WebSocket close flow.

Be aware that WebSocket close codes are very strictly defined, and the close reason phrase/message cannot exceed 123 characters in length (this is an intentional WebSocket limitation).

But not all is lost, if you are just wanting this information for debugging reasons, the detail of the closure, and its underlying reason is often reported with a fair amount of detail in Chrome's Javascript console.

Solution 2 - Javascript

In my and possibly @BIOHAZARD case it was nginx proxy timeout. In default it's 60 sec without activity in socket

I changed it to 24h in nginx and it resolved problem

proxy_read_timeout 86400s;
proxy_send_timeout 86400s;

Solution 3 - Javascript

It looks like this is the case when Chrome is not compliant with WebSocket standard. When the server initiates close and sends close frame to a client, Chrome considers this to be an error and reports it to JS side with code 1006 and no reason message. In my tests, Chrome never responds to server-initiated close frames (close code 1000) suggesting that code 1006 probably means that Chrome is reporting its own internal error.

P.S. Firefox v57.00 handles this case properly and successfully delivers server's reason message to JS side.

Solution 4 - Javascript

Thought this might be handy for others. Knowing regex is useful, kids. Stay in school.

Edit: Turned it into a handy dandy function!

let specificStatusCodeMappings = {
    '1000': 'Normal Closure',
    '1001': 'Going Away',
    '1002': 'Protocol Error',
    '1003': 'Unsupported Data',
    '1004': '(For future)',
    '1005': 'No Status Received',
    '1006': 'Abnormal Closure',
    '1007': 'Invalid frame payload data',
    '1008': 'Policy Violation',
    '1009': 'Message too big',
    '1010': 'Missing Extension',
    '1011': 'Internal Error',
    '1012': 'Service Restart',
    '1013': 'Try Again Later',
    '1014': 'Bad Gateway',
    '1015': 'TLS Handshake'
};

function getStatusCodeString(code) {
    if (code >= 0 && code <= 999) {
        return '(Unused)';
    } else if (code >= 1016) {
        if (code <= 1999) {
            return '(For WebSocket standard)';
        } else if (code <= 2999) {
            return '(For WebSocket extensions)';
        } else if (code <= 3999) {
            return '(For libraries and frameworks)';
        } else if (code <= 4999) {
            return '(For applications)';
        }
    }
    if (typeof(specificStatusCodeMappings[code]) !== 'undefined') {
        return specificStatusCodeMappings[code];
    }
    return '(Unknown)';
}

Usage:

getStatusCodeString(1006); //'Abnormal Closure'

{
    '0-999': '(Unused)',
    '1016-1999': '(For WebSocket standard)',
    '2000-2999': '(For WebSocket extensions)',
    '3000-3999': '(For libraries and frameworks)',
    '4000-4999': '(For applications)'
}

{
    '1000': 'Normal Closure',
    '1001': 'Going Away',
    '1002': 'Protocol Error',
    '1003': 'Unsupported Data',
    '1004': '(For future)',
    '1005': 'No Status Received',
    '1006': 'Abnormal Closure',
    '1007': 'Invalid frame payload data',
    '1008': 'Policy Violation',
    '1009': 'Message too big',
    '1010': 'Missing Extension',
    '1011': 'Internal Error',
    '1012': 'Service Restart',
    '1013': 'Try Again Later',
    '1014': 'Bad Gateway',
    '1015': 'TLS Handshake'
}

Source (with minor edits for terseness): https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes

Solution 5 - Javascript

I've got the error while using Chrome as client and golang gorilla websocket as server under nginx proxy

And sending just some "ping" message from server to client every x second resolved problem

Update: Oh boy I implemented dozens of websocket based apps after this answer and PINGING FROM CLIENT every 5 seconds is the correct way to keep connection with server alive (I do not know what was in my mind when I was recommending to ping from server)

Solution 6 - Javascript

Adding this as one of the possible reasons rather than answer to the question.

The issue we had affected only chromium based browsers.

We had a load balancer & the browser was sending more bytes than negotiated during handshake resulting in the load balancer terminating the connection.

TCP windows scaling resolved the issue for us.

Solution 7 - Javascript

This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )

Solution 8 - Javascript

We had the same problem and actually AWS was our problem.

Setup Websocket connection -> AWS EC2 Loadbalancer -> Nginx Proxy -> Node.js Backend

We increase the timeout based on this answer above in the Nginx conf but didn't see any improvements. We now found out that the AWS Loadbalancer also has a timeout that defaults to 60s. You can edit it under EC2 -> Loadbalancers enter image description here.

Note that we didn't implement a ping-pong scheme. We think that implementing one would also fix the problem until then we just use this workaround and increase the idle timeout.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionslevinView Question on Stackoverflow
Solution 1 - JavascriptJoakim ErdfeltView Answer on Stackoverflow
Solution 2 - Javascriptmixalbl4View Answer on Stackoverflow
Solution 3 - Javascriptuser10663464View Answer on Stackoverflow
Solution 4 - JavascriptAndrewView Answer on Stackoverflow
Solution 5 - JavascriptBIOHAZARDView Answer on Stackoverflow
Solution 6 - JavascriptAswin SakethView Answer on Stackoverflow
Solution 7 - JavascriptAnkush SahuView Answer on Stackoverflow
Solution 8 - JavascriptJohn DoeView Answer on Stackoverflow