html - ws 如何捕获:WebSocket 连接到 'ws://failed:连接建立时出错:net::ERR_CONNECTION_REFUSED

标签 html websocket

我有简单的 web 套接字 html5,当服务器启动时一切正常 问题是当我关闭服务器时(用于测试) 我得到:

WebSocket connection to 'ws://127.0.0.1:7777/api' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

如果发生此错误,我无法捕捉到它永远不会跳转到 onerror 或 onclose

init: function () {
           this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");

           this.m_wsiSendBinary.onopen = function(evt) {
               cc.log("Send Binary WS was opened.");
           };

           this.m_wsiSendBinary.onmessage = (function(evt) {


               this.handleServerResponse(yStr);


           this.m_wsiSendBinary.onerror = function(evt) {

           };

           this.m_wsiSendBinary.onclose = function(evt) {
               cc.log("m_wsiSendBinary websocket instance closed.");
               self.m_wsiSendBinary = null;
           };

}).bind(this);

最佳答案

我没有完整的答案,但是我处理过类似的问题并且有一个部分的而不是那么优雅的解决方案(但可能会帮助某人)。不幸的是没有消除错误信息。

两个业务需求:

  • BR1 - 在服务器不可用时处理初始化状态。
  • BR2 - 服务器停止时处理状态。

BR1 的解决方案

var global_connection_openned=null;//Here you have the result
init: function () {
       global_connection_openned=false;
       this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");
       this.m_wsiSendBinary.onopen = function(evt)
          {
             global_connection_openned=true;
          };

BR2 的解决方案(假设是 BR1)

//somewhere in your project called by setInterval(..) which will detect the connection is lost (and tries to reestablish/reopen the connetion.
{
  if (this.m_wsiSendBinary==null || this.m_wsiSendBinary.readyState==3)
    this.init();

  if (!global_connection_openned)
    this.m_wsiSendBinary=null;
}

无论如何,我真的很好奇这个用例是否有可靠和适当的解决方案。

关于html - ws 如何捕获:WebSocket 连接到 'ws://failed:连接建立时出错:net::ERR_CONNECTION_REFUSED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38670023/

相关文章:

html - 如何制作无法滚动的页面?

javascript - 如何在 html 中创建动态/ self 调整表格,在 Excel/电子表格中显示数据库

javascript - 切换所有 div 元素的文本颜色

python - 如何获取 Tornado Web 套接字请求的客户端 IP?

javascript - 使用 websocket 在浏览器和 java SE 项目之间传递数据

javascript - 谷歌图片搜索鼠标悬停,它们是如何工作的?

php - CodeIgniter - radio 输入上的 PHP Set_Radio

node.js - Nestjs @SubscribeMessage UnhandledPromiseRejectionWarning : TypeError: this. contextUtils.getContextFactory 不是函数

http - Socket.io 不设置 CORS header

javascript - Node 中有没有一个好的库用于客户端和服务器之间的异步通信?