发送数据用触发器,接收数据是实时的,服务器端发送的数据实时处理:
接收数据方法:
let sx = new WebSocket(shuxingweizhi.wsapi + “/websocket/” + allMess.userdq.uidname);
sx.onopen = function () {
console.log(“已连接!”);
allMess.txWebSocket = sx;//存起来全局使用 方便发送信息
sx.send(JSON.stringify(allMess.userdq));
}
sx.onmessage = function (evt) {
if (typeof evt.data == 'string') {
var r_msg = evt.data;
//var ms: string = "<br/>接收的信息为:" + r_msg;
_this.heriUser(r_msg);
// console.log(ms);
} else { }
};//接收时自己也会接收,可以自己设置过滤的if语句
sx.onclose = function () {
// 关闭 websocket
console.log("链接关闭");
};
在需要发送数据的地方(例如走动 拾取 攻击):
调用这个方法
socketSendSinday() {
let _this = this;
if (null != allMess.txWebSocket) {
//console.log("连接状态:"+allMess.txWebSocket.readyState);
if (allMess.txWebSocket.readyState == 1) {
allMess.txWebSocket.send(JSON.stringify(allMess.userdq));
} else if (allMess.txWebSocket.readyState == 3) {
//重新联动
let sx = new WebSocket(shuxingweizhi.wsapi + "/websocket/" + allMess.userdq.uidname);
sx.onmessage = allMess.txWebSocket.onmessage;
sx.onclose = allMess.txWebSocket.onclose;
console.log("第" + _this.timeConnectSize + "次重连");
if (_this.timeConnectSize == 0) {
_this.timeConnectSize = _this.timeConnectSize + 1;
//_this.schedule(function () {
sx.onopen = function () {
allMess.txWebSocket = sx;
allMess.txWebSocket.send(JSON.stringify(allMess.userdq));
let ybmes = find(shuxingweizhi.centerMess);
ybmes.getComponent(UIOpacity).opacity = 225;
ybmes.getComponent(RichText).string = '已重新连接!';
let sb: number = 225;
_this.schedule(function () {
// 这里的 this 指向 component
sb = sb - 25;
ybmes.getComponent(UIOpacity).opacity = sb;
}, 0.05, 9, 0);
console.log("已经重新连接");
_this.timeConnectSize = 0;
return;
}
//}, 2, 1, 0);
} else {
}
//_this.timeConnect = _this.timeConnect + 1;
}
}
}