zhuguoqing c21cd97580 udpate
2022-05-26 14:48:21 +08:00

102 lines
3.6 KiB
JavaScript

// Learn cc.Class:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
var Sock = cc.Class({
name: "Sock",
properties: {
// foo: {
// // ATTRIBUTES:
// default: null, // The default value will be used only when the component attaching
// // to a node for the first time
// type: cc.SpriteFrame, // optional, default is typeof default
// serializable: true, // optional, default is true
// },
// bar: {
// get () {
// return this._bar;
// },
// set (value) {
// this._bar = value;
// }
// },
},
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
// update (dt) {},
__ctor__(callback, hosturl){
//this._super();
this._sock = null;
this._cb = callback;
this._host = hosturl;
this._sendqueue = [];
this._isclosed = false;
var self = this;
if(typeof(WebSocket) != 'undefined'){
//cocos creator websocket
this._sock = new WebSocket(hosturl,[], cc.uiHelper.wssCacert.nativeUrl);
this._sock.binaryType = 'arraybuffer';
this._sock.onmessage = function (event) {
//console.log("socket on message");
self._cb.onMessage && self._cb.onMessage(event.data);
};
this._sock.onopen = function (event) {
console.log("Create the socket is success :"+self._host );
while (self._sendqueue.length > 0) {
self._sock.send(self._sendqueue.pop());
}
self._cb.onOpen && self._cb.onOpen(self._host);
};
this._sock.onclose = function (e) {
self._isclosed = true;
self._cb.onClose && self._cb.onClose(self._host,e);
// cc.director.emit('socketClose');
console.log("socket on closed ,code:"+e.code+"(1000:NORMAL,1005:CLOSE_NO_STATUS,1006:RESET,1009:CLOSE_TOO_LARGE) msg:"+e.reason);
};
this._sock.onerror = function (event) {
if(!self._isclosed){
self.close();
}
self._isclosed = true;
console.log("socket on error ,event:"+JSON.stringify(event));
self._cb.onError && self._cb.onError(self._host,event);
};
}else if(typeof(wx) != 'undefined'){
}
},
send(msg){
var n = this._sock.readyState;
//console.log("sock readyState:" + n);
if(n == WebSocket.CONNECTING){
this._sendqueue.push(msg);
}else if(n == WebSocket.OPEN){
this._sock.send(msg);
}else{
this._sock.onclose({code:-n});
}
},
close(){
//todo:
this._sendqueue.length=0;
this._sock && this._sock.close();
}
});
module.exports = Sock;