gpt4 book ai didi

javascript - 是否可以在浏览器中使用 websocket 等待服务器?

转载 作者:行者123 更新时间:2023-11-28 01:24:04 25 4
gpt4 key购买 nike

我想在浏览器 (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”,则会收到警报“连接已关闭”,即使启动服务器,我也不会在控制台上收到“连接已建立”。它仅在我单击“运行 WebSocket”之前服务器正在运行时有效。如何让它发挥作用?

最佳答案

我认为你在 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..很难描述..请阅读评论中注明的示例;)

关于javascript - 是否可以在浏览器中使用 websocket 等待服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22931977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com