我正在尝试在我的项目中实现webrtc通信。我已使用appr.tc代码库进行开发。该代码库包含用于chrome&firefox浏览器的两个单独的websocket实现。
if (isChromeApp()) {
this.websocket_ = new RemoteWebSocket(this.wssUrl_, this.wssPostUrl_);
} else {
this.websocket_ = new WebSocket(this.wssUrl_);
}
RemoteWebSocket
var RemoteWebSocket = function (wssUrl, wssPostUrl) {
this.wssUrl_ = wssUrl;
apprtc.windowPort.addMessageListener(this.handleMessage_.bind(this));
this.sendMessage_({ action: Constants.WS_ACTION, wsAction: Constants.WS_CREATE_ACTION, wssUrl: wssUrl, wssPostUrl: wssPostUrl });
this.readyState = WebSocket.CONNECTING;
};
RemoteWebSocket.prototype.sendMessage_ = function (message) {
apprtc.windowPort.sendMessage(message);
};
RemoteWebSocket.prototype.send = function (data) {
if (this.readyState !== WebSocket.OPEN) {
throw "Web socket is not in OPEN state: " + this.readyState;
}
this.sendMessage_({ action: Constants.WS_ACTION, wsAction: Constants.WS_SEND_ACTION, data: data });
};
RemoteWebSocket.prototype.close = function () {
if (this.readyState === WebSocket.CLOSING || this.readyState === WebSocket.CLOSED) {
return;
}
this.readyState = WebSocket.CLOSING;
this.sendMessage_({ action: Constants.WS_ACTION, wsAction: Constants.WS_CLOSE_ACTION });
};
RemoteWebSocket.prototype.handleMessage_ = function (message) {
if (message.action === Constants.WS_ACTION && message.wsAction === Constants.EVENT_ACTION) {
if (message.wsEvent === Constants.WS_EVENT_ONOPEN) {
this.readyState = WebSocket.OPEN;
if (this.onopen) {
this.onopen();
}
} else {
if (message.wsEvent === Constants.WS_EVENT_ONCLOSE) {
this.readyState = WebSocket.CLOSED;
if (this.onclose) {
this.onclose(message.data);
}
} else {
if (message.wsEvent === Constants.WS_EVENT_ONERROR) {
if (this.onerror) {
this.onerror(message.data);
}
} else {
if (message.wsEvent === Constants.WS_EVENT_ONMESSAGE) {
if (this.onmessage) {
this.onmessage(message.data);
}
} else {
if (message.wsEvent === Constants.WS_EVENT_SENDERROR) {
if (this.onsenderror) {
this.onsenderror(message.data);
}
console.log("ERROR: web socket send failed: " + message.data);
}
}
}
}
}
}
};
我不想关闭WebSocket连接。在Internet连接断开的情况下(3分钟内),RemoteWebSocket在chrome浏览器上工作正常。 3分钟内连接断开时,没有关闭事件发生。但是在firefox中,WebSocket连接将立即关闭。
有什么方法可以延迟javascript websocket libray中的close事件吗?
答案 0 :(得分:0)
之所以这样,是因为Web套接字连接的设计方式是在没有网络时断开连接。我了解您不希望您的套接字断开连接,因此,一旦网络连接恢复,您将必须编写逻辑来重新连接。因此,基本上,您将必须跟踪与WebSocket关联的数据结构,并在尝试重新连接时将其还原。