【问题标题】:Is it possible to wait for server using websockets in browser?是否可以在浏览器中使用 websockets 等待服务器?
【发布时间】:2014-04-08 08:47:28
【问题描述】:

我想在浏览器 (Chrome) 和 Android 手机之间建立连接。我有一个应该一直打开的网页,并且应该等待在 Android 上的某个事件启动的服务器。

我的代码:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function waitForSocketConnection(socket, callback){
    setTimeout(
        function () {
            if (socket.readyState === 1) {
                console.log("Connection is made")
                if(callback != null){
                    callback();
                }
                return;

            } else {
                console.log("wait for connection...")
                waitForSocketConnection(socket);
            }

        }, 5); // wait 5 milisecond for the connection...
}
function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     alert("WebSocket is supported by your Browser!");
     // Let us open a web socket
     var ws = new WebSocket("ws://192.168.0.15:8887");
     waitForSocketConnection(ws, function() {alert('callback')})
     ws.onopen = function()
     {
        // Web Socket is connected, send data using send()
        ws.send("Message to send");
        alert("Message is sent...");
     };
     ws.onmessage = function (evt) 
     { 
        var received_msg = evt.data;
        alert("Message is received...");
     };
     ws.onclose = function()
     { 
        // websocket is closed.
        alert("Connection is closed..."); 
     };

  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}
</script>
</head>
<body>
<div id="sse">
   <a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>

如果我在服务器未运行时单击运行 WebSocket,则会收到警报“连接已关闭”,即使我启动服务器,控制台上也不会出现“连接已建立”。它仅在我单击 Run WebSocket 之前服务器正在运行时才有效。如何让它发挥作用?

【问题讨论】:

  • 这个问题属于android吗?你在哪里得到这个错误连接已关闭”??
  • 只是浏览器 (html5) websockets。我在浏览器中收到此消息。只有服务器在 Android 上运行。
  • 你有没有从android端得到任何错误
  • 没有。 android 服务器上没有任何动作。我认为这只是JS的问题

标签: javascript websocket


【解决方案1】:

我认为你在WebSocketTest 中遗漏了一些东西......

  • ws.onclose 中,您应该再次调用ws = new WebSocket.. 以在错误/断开连接时重新连接...

通常等待服务器可用是这样的

var ws = new WebSocket(host);
// if no connection is available or error occurred
ws.onclose = function() {
  // wait a bit and retry, don't flood the network ;)
  setTimeout( function(){ ws = new WebSocket(host); }, 100 );
}

同样,您不必显式检查就绪状态 - 只需将您的代码放入 ws.onopen


编辑:

arr.. 难以描述.. 请阅读评论中提到的示例;)

【讨论】:

    【解决方案2】:

    我正在执行以下操作来准备我的 WebSocket,以便在许多其他地方使用,而不仅仅是在 WebSocket readyState 更改之后:

    // https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
    const sleep = (ms) => {
      return new Promise(resolve => setTimeout(resolve, ms));
    };
    
    // (inside of async function)...
    
      const ws = new WebSocket(<webSocketServerUri>);
    
      let timeToConnect = 0;
      while (ws.readyState !== ws.OPEN) {
        await sleep(1);
        ++timeToConnect;
      };
    
      console.log('The WebSocket took ' + timeToConnect + ' milliseconds to connect.');
    
    // (inside of async function)...
    // ...
    // (some other place in the code where 'ws' is accessible)...
    
      ws.send('my msg');
    
    // (some other place in the code where 'ws' is accessible)...
    

    【讨论】:

      猜你喜欢
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      相关资源
      最近更新 更多