WebSocket 未显示 js 警报

时间:2021-05-11 16:30:29

标签: javascript php websocket

有人告诉我,我的另一篇 SO 帖子中的解决方案可能涉及 WebSocket。它只是在与我的 Url 一起使用时立即关闭连接,但 javascript.info Url 工作正常。但这是为什么呢?

console.log 说:

WebSocket connection to 'wss://verlager.com/hello' failed: 

function sentry() {
  if ("WebSocket" in window) {
    console.log("WebSocket is supported by your Browser!");

    // Let us open a web socket
    
    // THIS WORKS:
    let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");
    
    // But my server doesn't work! Why doesn't it work on my server?
    var ws = new WebSocket("wss://verlager.com/hello");

    ws.onopen = function() {
      // Web Socket is connected, send data using send()
      ws.send("Message to send");
      console.log("Message is sent...");
    };

    ws.onmessage = function (evt) { 
      var received_msg = evt.data;
      console.log("Message is received...");
    };

    ws.onclose = function() { 
      // websocket is closed.
      console.log("Connection is closed..."); 
    };
  } else {
    // The browser doesn't support WebSocket
    console.log("WebSocket NOT supported by your Browser!");
  }
}
sentry();

1 个答案:

答案 0 :(得分:0)

抱歉将其作为答案发布,我没有足够的代表发表评论。

首先,当我尝试连接到未运行的 wss://localhost 时,我遇到了格式完全相同的错误。 尝试指定您的服务器的端口,我不确定默认情况下它采用哪一个。还要确保您的服务器正在运行安全的 websockets 并且它正确处理您的路径 /hello

相关问题