我想在浏览器(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>
如果我在服务器没有运行时单击Run WebSocket,那么我会收到警告“Connection is closed”,即使我启动了服务器,我也没有在控制台上获得“Connection is made”。它仅在我单击Run WebSocket之前运行服务器时有效。如何使它工作?
答案 0 :(得分: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 ..难以描述..请阅读评论中注明的例子;)
答案 1 :(得分:0)
我正在做以下准备,以准备在许多其他地方使用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)...