摘要
在 Cocos Creator 中,我们使用WebSocket:用于长连接,今天我们说一下长连接的封装。
使用WebSocket作为网络连接的方式,简单的使用文本传输,使用onfire做事件的分发,可以替换NetControl里面的websocket实现为socket和其他网络方案,只要修复onfire的激发,基本不用该游戏代码。
环境
cocos Creator 引擎2.4.3
编辑工具HBuild X
使用方法
1、引入一个onfire类库
引入一个onfire类库
项目地址:
https://github.com/hustcc/onfire.js
2、websocket的封装
window.onfire = require("./onfire");//处理事件的类库
//websocket定义
cc.websocket = {
_sock: {}, //当前的webSocket的对象
lockReconnect: false,
times: 1,
host: "wss://g.XXX.com", //这里接口地址
connect: function (res) {
if (this._sock.readyState !== 1) {
this._sock = new WebSocket(this.host);
this._sock.onopen = this._onOpen.bind(this);
this._sock.onclose = this._onClose.bind(this);
this._sock.onmessage = this._onMessage.bind(this);
this._sock.onerror = this._onError.bind(this);
}
return this;
},
_onOpen: function (res) {
this.times = 1;
console.log("连接成功!"+this.host);
},
_onClose: function (err) {
onfire.fire("onclose",err);
console.log(this.host+"执行的是onClose函数!"+err);
},
_onMessage: function (res) {
var Data = JSON.parse(res.data);
if (Data.action == 'error') {
cc.vv.message(Data.msg);
} else {
onfire.fire("onmessage", Data);
}
},
_onError: function (err) {
console.log(this.host+"执行的是onError函数"+err);
},
send: function (msg) {
var _this = this;
setTimeout(() => {
if (_this._sock.readyState == 1) {
_this._sock.send(JSON.stringify(msg));
}
}, 0)
}
};
在代码中使用封装的websocket,代码实例比如说登录
var smData = {
action: 'login',
username: username,
password: password,
};
cc.websocket.send(smData);
解除onfire的注册绑定与解除
绑定
onMessage(res) {
var _sthi = this;
try {
_sthi[res.action](res);
} catch (e) {
console.log('onmessage(' + res.action + ')' + e);
}
},
onLoad() {
onfire.on("onmessage", this.onMessage.bind(this));
},
解除
onfire.clear();
结语:
欢迎加入微信群一起学习讨论!