javascript 获取关闭代码 1006 关闭 websockets 的原因

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19304157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:05:35  来源:igfitidea点击:

getting the reason why websockets closed with close code 1006

javascriptwebsocket

提问by slevin

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

我想知道 websockets 关闭的原因,所以我可以向用户显示正确的消息。

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.

代码始终为 1006,原因始终为“ ”。但我想区分不同的关闭原因。

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 " ".

例如,命令行给出了一个错误原因:“你不能删除那个,因为数据库不会让你”。但是在Chrome的控制台上,原因还是“ ”。

Any other way to tell different closing reasons apart?

还有其他方法可以区分不同的关闭原因吗?

回答by Joakim Erdfelt

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

关闭代码1006是一种特殊代码,表示浏览器实现异常(本地)关闭了连接。

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

如果您的浏览器客户端报告 close code 1006,那么您应该查看websocket.onerror(evt)事件以获取详细信息。

However, Chrome will rarely report any close code 1006reasons 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).

但是,Chrome 很少会1006向 Javascript 端报告任何关闭代码的原因。这可能是由于 WebSocket 规范中的客户端安全规则可以防止滥用 WebSocket。(例如使用它来扫描目标服务器上的开放端口,或为拒绝服务攻击生成大量连接)。

Note that Chrome will often report a close code 1006if 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/)

请注意,1006如果在 HTTP 升级到 Websocket 期间出现错误(这是技术上“连接”WebSocket 之前的步骤),Chrome 通常会报告关闭代码。由于错误的身份验证或授权,或错误的协议使用(例如请求子协议,但服务器本身不支持相同的子协议),甚至尝试与不是 WebSocket 的服务器位置通信(例如尝试连接到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.

从根本上说,如果你看到一个关闭的代码1006,你有一个非常低级的 WebSocket 错误(类似于“无法打开文件”或“套接字错误”),并不是真正针对用户的,因为它指向一个低级问题与您的代码和实现。修复您的低级问题,然后当您连接时,您可以包含更合理的错误代码。您可以根据项目的范围或严重性来实现这一点。示例:信息和警告级别是项目特定协议的一部分,不会导致连接终止。对于严重或致命的消息报告,还使用您的项目协议来传达您想要的尽可能多的细节,然后使用 WebSocket 关闭流的有限功能关闭连接。

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).

请注意,WebSocket 关闭代码的定义非常严格,关闭原因短语/消息的长度不能超过 123 个字符(这是一个有意的 WebSocket 限制)。

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.

但并不是所有的都丢失了,如果您只是出于调试原因想要这些信息,那么关闭的详细信息及其根本原因通常会在 Chrome 的 Javascript 控制台中以相当多的详细信息报告。

回答by user10663464

It looks like this is the case when Chrome is not compliant with WebSocket standard. When the server initiates closeand 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.

当 Chrome 不符合 WebSocket 标准时,情况似乎就是这种情况。当服务器发起关闭并向客户端发送关闭帧时,Chrome 认为这是一个错误,并向 JS 端报告代码 1006 和无原因消息。在我的测试中,Chrome 从不响应服务器启动的关闭帧(关闭代码 1000),这表明代码 1006 可能意味着 Chrome 正在报告自己的内部错误。

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

PS Firefox v57.00 正确处理了这种情况,并成功地将服务器的原因消息传递给了 JS 端。

回答by MixerOID

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

在我和可能的@BIOHAZARD 案例中,它是nginx proxy timeout. 默认情况60下,套接字中没有活动是秒

I changed it to 24h in nginxand it resolved problem

我将其更改为 24hnginx并解决了问题

proxy_read_timeout 86400s;
proxy_send_timeout 86400s;

回答by Andrew

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

来源(为简洁起见略作修改):https: //developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes

回答by BIOHAZARD

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

在 nginx 代理下使用 Chrome 作为客户端并使用 golang gorilla websocket 作为服务器时出现错误

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

并且每隔 x 秒从服务器向客户端发送一些“ping”消息解决了问题

回答by Ankush Sahu

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

这可能是您在设备中使用的 websocket URL 不相同(您从 android/iphonedevice 访问不同的 websocket URL)