Javascript 检查 WebSocket 服务器是否正在运行(在本地主机上)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42112919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if WebSocket Server is running (on localhost)
提问by Jakob
When I try to initialize a websocket connection to the server running on localhost with
当我尝试初始化与本地主机上运行的服务器的 websocket 连接时
var webSocket = new WebSocket("ws://localhost:8025/myContextRoot");
in javascript, but the server hasn't completed starting up yet, I get the error
在 javascript 中,但服务器尚未完成启动,我收到错误
SCRIPT12029: WebSocket Error: Network Error 12029, A connection with the server could not be established
SCRIPT12029:WebSocket 错误:网络错误 12029,无法建立与服务器的连接
How can I prevent this? I.e. how do I check if the server has already started or how can I force the WebSocket client to wait for the server?
我怎样才能防止这种情况?即如何检查服务器是否已经启动或者如何强制 WebSocket 客户端等待服务器?
回答by Matías Fidemraizer
What about:
关于什么:
var webSocketFactory = {
connectionTries: 3,
connect: function(url) {
var ws = new WebSocket(url);
ws.addEventListener("error", e => {
// readyState === 3 is CLOSED
if (e.target.readyState === 3) {
this.connectionTries--;
if (this.connectionTries > 0) {
setTimeout(() => this.connect(url), 5000);
} else {
throw new Error("Maximum number of connection trials has been reached");
}
}
});
}
};
var webSocket = webSocketFactory.connect("ws://localhost:8025/myContextRoot");
When you get a connection error, you can do a limited number of trial-errors to try to re-connect. Or you can endlessly try to reach the server.
当您遇到连接错误时,您可以进行有限次数的试错以尝试重新连接。或者您可以无休止地尝试访问服务器。
回答by Redu
The accepted answer is perfectly fine. I just would like to extend it a little bit further with promises.
接受的答案非常好。我只是想通过承诺进一步扩展它。
var wsFactory = { tryCount: 3,
connect : function(url){
var ctx = this,
ws = new WebSocket(url);
return new Promise(function(v,x){
ws.onerror = e => { console.log(`WS connection attempt ${4-ctx.tryCount} -> Unsuccessful`);
e.target.readyState === 3 && --ctx.tryCount;
if (ctx.tryCount > 0) setTimeout(() => v(ctx.connect(url)), 1000);
else x(new Error("3 unsuccessfull connection attempts"));
};
ws.onopen = e => { console.log(`WS connection Status: ${e.target.readyState}`);
v(ws);
};
ws.onmessage = m => console.log(m.data);
});
}
};
wsFactory.connect("ws://localhost:8025/myContextRoot")
.then(ws => ws.send("Hey..! This is my first socket message"))
.catch(console.log);
回答by m87
You can't prevent (or put on hold) the WebSocket from starting / establish a connection. WebSocket automatically establishes a connection with the server when its declared. What you can do is place all your code inside onopenevent handler that you want to execute on successful connection. So it would be like...
您无法阻止(或暂停)WebSocket 启动/建立连接。WebSocket 在声明时自动与服务器建立连接。您可以做的是将所有代码放在onopen要在成功连接时执行的事件处理程序中。所以它会像...
var webSocket = new WebSocket("ws://localhost:8025/myContextRoot");
webSocket.onopen = function() {
// code you want to execute
};
check thisarticle to know more about WebSocket.
检查此文章了解更多有关的WebSocket。
回答by Feirell
Hence the protocol can't get queried by the server if it is not started, the only option is trial and error.
因此,如果协议未启动,则服务器无法查询该协议,唯一的选择是反复试验。
Or you could let the WebSocket server create a simple textfile with the timestamp of the startup in your web space directory where the javascript can retrieve it and than try to establish a connection. You can retrieve the textfile with XMLHttpRequest.
或者,您可以让 WebSocket 服务器在您的 Web 空间目录中创建一个带有启动时间戳的简单文本文件,javascript 可以在其中检索它,然后尝试建立连接。您可以使用XMLHttpRequest检索文本文件。

