无法使用javascript连接网络套接字

无法使用javascript连接网络套接字

问题描述:

我想连接到我的网络套接字,该套接字使用某些ip放在amazone实例上。我可以连接我的网络套接字与一些IP和端口与谷歌休息客户端应用程序,它的工作得很好。 屏幕截图: enter image description here无法使用javascript连接网络套接字

但是,如果我想连接这个与java脚本它不能连接。这在2-3个月前工作正常。我没有改变,但现在不工作。 如果我想连接到Firefox,它会产生一个错误。 这里是我的代码: -

function init() { 
      var host = "ws://XX.XX.XXX.XXX:XXXX"; // SET THIS TO YOUR SERVER 


       try { 
        var socket = new WebSocket(host); 
        // alert('WebSocket - status ' + socket.readyState); 
        log('WebSocket - status ' + socket.readyState); 

        socket.onopen = function (msg) { 
         alert('open'); 
         alert("Welcome - status " + this.readyState); 
         log("Welcome - status " + this.readyState); 

         if (this.readyState != 1) 
         { 
          reconnect(); 
         } 
        }; 
        socket.onmessage = function (msg) { 
         // alert("Received: " + msg.data); 
         log("Received: " + msg.data); 

        }; 
        socket.onclose = function (msg) { 
        // alert("Disconnected - status " + this.readyState); 
         log("Disconnected - status " + this.readyState); 
        }; 
       } catch (ex) { 
        alert(ex); 
        log(ex); 
       } 
       $("msg").focus(); 
      } 

这是警报状态0和错误显示在控制台: -

Firefox can't establish a connection to the server at ws://XX.XX.XXX.XXX:XXXX. 


var socket = new WebSocket(host); 
+0

你可以从机器ping你的IP连接错误?另外检查websocket服务器运行 –

+0

websocket正在运行,也与谷歌休息客户端应用程序连接,你可以在屏幕上看到它只给网页带来错误。 –

我会尝试你的代码,对我来说工作得很好,我请使用此网页进行测试:https://www.websocket.org/echo.html,可能对测试有帮助。但我也发现这个问题:websocket-rails, websocket handshake error,也许也有帮助。 但是我只是把你的代码中的主机改为:“ws://echo.websocket.org”,并且一切正常。 希望你找到一个解决方案,这个信息是任何帮助。以下是我用于测试的代码:

function init() { 
var host = "ws://echo.websocket.org"; 
    try { 
     var socket = new WebSocket(host); 
     alert('WebSocket - status ' + socket.readyState); 
     socket.onopen = function (msg) { 
      alert('open'); 
      alert("Welcome - status " + this.readyState); 

      if (this.readyState != 1) 
      { 
       reconnect(); 
      } 
     }; 
     socket.onmessage = function (msg) { 
      alert("Received: " + msg.data); 
     }; 
     socket.onclose = function (msg) { 
      alert("Disconnected - status " + this.readyState); 
     }; 
    } catch (ex) { 
     alert(ex); 

    } 
    $("msg").focus(); 
} 

*对不起,我的英文不好。

+0

我已经测试过这个网络套接字,它工作正常,但不适用我的套接字。但它可以连接到谷歌休息客户端套接字连接,你可以看到截图。我做错了什么。 –

+0

这与我的插座连接,但自动断开连接。 –

+0

好吧,很难重现你得到的错误,因为我不知道你的网络套接字。也许你已经尝试过了,但我仍然会问,你是否尝试将“ws”更改为“wss”?...我再次尝试使用其他套接字的代码,并得到与您一样的错误,然后我只更改为“wss :// xxxx:xxxx“,它适用于我在Firefox中的工作。 – Maxter