我正在使用HTML5套接字函数来建立到服务器的套接字连接。HTML5有以下函数来处理断开连接
Socket.onclose = function()
{
...
}
Socket.onerror = function()
{
...
}
我的问题是,如何尝试在onclose函数执行后重新连接?我试着在里面放一个while循环,比如
ws.onclose = function()
{
While(conn==0)
{
ws = new WebSocket("ws://example.com");
}
}
和
ws.onopen = function()
{
conn=1;
...
}
但不工作。
任何想法?
这是Plezi websocket框架自带的脚本…它相当基础,但在我使用它的浏览器(Safari、Chrome和FireFox)上都能运行。
技巧是利用没有循环的onclose
方法。
onclose
方法将被调用,即使websocket从未打开并且连接无法建立(不调用onopen
)。
启动一个onclose
内的重新连接就足够了。
编写循环或条件审查不仅会失败,而且会停止页面上的所有脚本。请允许我解释一下:
-
Javascript是单线程的。再次强调:这是一个基于偶数/任务的单线程环境。
这意味着你的代码就像一个原子单元——在你的代码完成运行之前,什么都不会发生,什么都不会改变。
-
因为连接可能需要一段时间来建立,所以
new WebSocket
被设计为异步函数(这是正确的)。这就是为什么你可以在事件创建后定义
onopen
事件回调 -
只在当前任务/事件完成后才尝试新的websocket连接…
…所以循环会让你永远等待一个任务不能执行,直到你的代码停止运行…
回到手头的问题,下面是代码。如果您有任何改进意见,请告诉我:
// Your websocket URI should be an absolute path. The following sets the base URI.
// remember to update to the specific controller's path to your websocket URI.
var ws_controller_path = window.location.pathname; // change to '/controller/path'
var ws_uri = (window.location.protocol.match(/https/) ? 'wss' : 'ws') + '://' + window.document.location.host + ws_controller_path
// websocket variable.
var websocket = NaN
// count failed attempts
var websocket_fail_count = 0
// to limit failed reconnection attempts, set this to a number.
var websocket_fail_limit = NaN
// to offer more or less space between reconnection attempts, set this interval in miliseconds.
var websocket_reconnect_interval = 250
function init_websocket()
{
if(websocket && websocket.readyState == 1) return true; // console.log('no need to renew socket connection');
websocket = new WebSocket(ws_uri);
websocket.onopen = function(e) {
// reset the count.
websocket_fail_count = 0
// what do you want to do now?
};
websocket.onclose = function(e) {
// If the websocket repeatedly you probably want to reopen the websocket if it closes
if(!isNaN(websocket_fail_limit) && websocket_fail_count >= websocket_fail_limit) {
// What to do if we can't reconnect so many times?
return
};
// you probably want to reopen the websocket if it closes.
if(isNaN(websocket_fail_limit) || (websocket_fail_count <= websocket_fail_limit) ) {
// update the count
websocket_fail_count += 1;
// try to reconect
setTimeout( init_websocket, websocket_reconnect_interval);
};
};
websocket.onerror = function(e) {
// update the count.
websocket_fail_count += 1
// what do you want to do now?
};
websocket.onmessage = function(e) {
// what do you want to do now?
console.log(e.data);
// to use JSON, use:
// var msg = JSON.parse(e.data); // remember to use JSON also in your Plezi controller.
};
}
// setup the websocket connection once the page is done loading
window.addEventListener("load", init_websocket, false);