cocos creator版本:v1.8.2
在没有网络的情况下,会触发连接超时,自动断开,但是不触发webSocket的onClose事件(有触发,但是是一分钟之后)
export default class Socket extends cc.EventTarget {
private _webSocket: WebSocket;
private _timeoutTimer;
/**
* 创建websocket连接,同时监听相关事件
* @event error
* @event close
* @event open
* @return WebSocket
*/
createConnect(url:string) {
let _webSocket = new WebSocket(url);
if (this._timeoutTimer) {
clearTimeout(this._timeoutTimer);
}
// 超过3秒,自动关闭
let timeOutTimer = setTimeout(function () {
try {
cc.log("连接超时,自动断开");
_webSocket.close();
// that.emit("close");
} catch (e) {
cc.log("关闭websocket出错", e);
}
}, 5000);
cc.log("startTimeoutTimer", typeof timeOutTimer, timeOutTimer);
this._timeoutTimer = timeOutTimer;
cc.log("--->>> websocket begin connect", curIdx, new Date().getTime());
// 绑定连接成功的回调方法
_webSocket.onopen = function () {
if (timeOutTimer!=null) {
clearTimeout(that._timeoutTimer);
}
cc.log("--->>> websocket connected", curIdx, new Date().getTime());
that.emit("open");
};
// 绑定消息接收的回调方法
_webSocket.onmessage = function (event: MessageEvent) {
that._lastAliveTime = new Date().getTime();
let rawData = event.data;
let jsonData: IResponseMsg = JSON.parse(rawData);
that.emit("message", {
response: jsonData,
rawData: rawData
});
};
// 绑定断开连接的回调方法
_webSocket.onclose = function (e: CloseEvent) {
if (timeOutTimer!=null) {
clearTimeout(timeOutTimer);
}
cc.log("--->>> websocket onclose", curIdx, new Date().getTime(), e);
that.emit("close");
};
// 绑定错误发生的回调方法
_webSocket.onerror = function (e: any) {
if (timeOutTimer!=null) {
clearTimeout(timeOutTimer);
}
cc.log("--->>> websocket onerror", curIdx, new Date().getTime(), e);
that.emit("error");
};
return _webSocket;
}