Browse Source

修改合约ws断掉后自动重新获取ws数据

master
liaoxinyu 1 month ago
parent
commit
3b3ae1a2b9
  1. 4
      src/api/contract.js
  2. 10
      src/api/server/Socket.js
  3. 321
      src/views/contract/handicap.vue
  4. 511
      src/views/contract/index.vue
  5. 188
      src/views/option/kline.vue

4
src/api/contract.js

@ -11,14 +11,14 @@ class Contract {
}
static getMarketInfo(data) {
return server.get(`/contract/getMarketInfo`, {params:data})
return server.get(`/contract/getMarketInfo`, {params:data,config:{loading:false}})
}
/**
* 获取合约市场
*/
static getMarketList(data) {
return server.get('/contract/getMarketList', {params:data})
return server.get('/contract/getMarketList', {params:data,config:{loading:false}})
}
/**

10
src/api/server/Socket.js

@ -180,7 +180,7 @@
class Socket {
constructor(link, ...args) {
// 修复1:确保 this.link 存的是字符串,方便后面断线重连
// 修复1:确保 this.link 存的是字符串,方便后面断线重连
if (link.constructor === WebSocket) {
this.socket = link;
this.link = link.url;
@ -196,7 +196,7 @@ class Socket {
this.heartBeatTimer = null;
// 新增:重连相关的标识符
// 新增:重连相关的标识符
this.reconnectTimer = null;
this.isReconnecting = false;
this.manualClose = false; // 判断是否是用户主动退出页面
@ -244,7 +244,7 @@ class Socket {
}
for (let item of datas) {
// 修复2:发送前必须检查状态,彻底解决 "CLOSING or CLOSED state" 报错!
// 修复2:发送前必须检查状态,彻底解决 "CLOSING or CLOSED state" 报错!
if (this.socket && this.socket.readyState === 1) {
this.socket.send(JSON.stringify(item));
} else {
@ -291,7 +291,7 @@ class Socket {
return this.readyState >= 2;
}
// 修复3:核心重连逻辑
// 修复3:核心重连逻辑
reconnect() {
// 如果是手动关闭(退出页面),或者正在重连中,则放弃重连
if (this.manualClose || this.isReconnecting) return;
@ -332,7 +332,7 @@ class Socket {
if (!this.manualClose) this.reconnect();
}
// 修复4:解决内存泄漏,用完立刻注销
// 修复4:解决内存泄漏,用完立刻注销
emit(data) {
return new Promise((resolve) => {
this.send(JSON.stringify(data));

321
src/views/contract/handicap.vue

@ -140,6 +140,17 @@ export default {
buyList: [],
tradeList: [],
newPriceObj: {},
//
wsOpenHandler: null,
wsMessageHandler: null,
collapseHandler: null,
//
isRetrying: false,
lastMessageTime: 0, //
watchdogTimer: null, //
watchdogTimeout: 5000 // 5
};
},
props: {
@ -197,6 +208,7 @@ export default {
if (this.symbol) {
this.getMarketInfo();
this.linkSocket();
this.startWatchdog();
}
bus.$on('collapse', msg => {
this.newPriceObj.price =this.symbol=='BTC'? (msg.close).toFixed(1):(msg.close).toFixed(3);
@ -215,26 +227,66 @@ export default {
},
beforeDestroy() {
this.unLink(this.symbol);
this.removeSocketListeners();
this.stopWatchdog();
},
//
methods: {
parseTime: date.parseTime,
omitTo: math.omitTo,
getMarketInfo() {
let data = {
symbol: this.symbol
};
Contract.getMarketInfo(data).then(res => {
this.sellList = res.swapSellList;
this.buyList = res.swapBuyList;
this.tradeList = res.swapTradeList;
// if(this.tradeList.length>0){
this.newPriceObj = this.tradeList[0];
// }
this.$emit("input", this.newPriceObj);
localStorage.setItem("price",this.newPriceObj.price)
});
},
// getMarketInfo() {
// let data = {
// symbol: this.symbol
// };
// Contract.getMarketInfo(data).then(res => {
// this.sellList = res.swapSellList;
// this.buyList = res.swapBuyList;
// this.tradeList = res.swapTradeList;
// // if(this.tradeList.length>0){
// this.newPriceObj = this.tradeList[0];
// // }
// this.$emit("input", this.newPriceObj);
// localStorage.setItem("price",this.newPriceObj.price)
// });
// },
// .catch
getMarketInfo() {
if (!this.symbol) return;
let data = { symbol: this.symbol };
Contract.getMarketInfo(data).then(res => {
this.isRetrying = false; //
this.sellList = res.swapSellList;
this.buyList = res.swapBuyList;
this.tradeList = res.swapTradeList;
if(this.tradeList && this.tradeList.length > 0){
this.newPriceObj = this.tradeList[0];
}
this.$emit("input", this.newPriceObj);
localStorage.setItem("price", this.newPriceObj.price);
}).catch(err => {
// 🔥 (Uncaught in promise)
console.error("盘口接口请求失败/超时,3秒后自动重试...", err);
//
if (!this.isRetrying) {
this.isRetrying = true;
setTimeout(() => {
this.isRetrying = false;
this.getMarketInfo(); //
// 便 WS
if (this.ws && !this.ws.checkOpen()) {
console.log("检测到网络较差,尝试重连 WebSocket...");
this.ws.reconnect();
}
}, 3000); // 3
}
});
},
//
getValue(amount) {
const arr = this.buyListShow
@ -243,75 +295,180 @@ export default {
let max = Math.max(...arr);
return math.division(amount, max, 2) * 100;
},
//
sendSubscribe() {
if (!this.ws || !this.ws.socket || this.ws.socket.readyState !== 1) return;
this.ws.send({ cmd: "sub", msg: this.msg.buy });
this.ws.send({ cmd: "sub", msg: this.msg.sell });
this.ws.send({ cmd: "sub", msg: this.msg.trade });
},
//
removeSocketListeners() {
if (this.wsOpenHandler && this.ws) {
this.ws.off("open", this.wsOpenHandler);
}
if (this.wsMessageHandler && this.ws) {
this.ws.off("message", this.wsMessageHandler);
}
},
// WebSocket
startWatchdog() {
this.stopWatchdog();
this.lastMessageTime = Date.now();
this.watchdogTimer = setInterval(() => {
const now = Date.now();
if (now - this.lastMessageTime > this.watchdogTimeout) {
console.error(`[看门狗报警] 已经 ${this.watchdogTimeout/1000} 秒没收到推送了!判定为后端假死!正在强行掐断并新建 WebSocket...`);
// 1. HTTP
this.getMarketInfo();
// 2. Socket
if (this.ws) {
//
if (this.ws.socket) {
this.ws.socket.close();
}
// reconnect
this.ws.isReconnecting = false;
this.ws.manualClose = false;
this.ws.reconnect();
}
// 3.
this.lastMessageTime = Date.now();
}
}, 5000); // 5
},
// 🔥
stopWatchdog() {
if (this.watchdogTimer) {
clearInterval(this.watchdogTimer);
this.watchdogTimer = null;
}
},
// WebSocket
linkSocket() {
if (!this.ws) return;
this.removeSocketListeners();
// open
this.wsOpenHandler = () => {
this.sendSubscribe();
};
this.ws.on("open", this.wsOpenHandler);
//
this.wsMessageHandler = res => {
let { data, msg, code, sub, type, status, cmd } = res;
if (sub == this.msg.buy || sub == this.msg.sell || sub == this.msg.trade) {
this.lastMessageTime = Date.now();
}
if (sub == this.msg.buy) {
this.buyList = data;
} else if (sub == this.msg.sell) {
this.sellList = data;
} else if (sub == this.msg.trade) {
this.tradeList.unshift(data);
this.tradeList.pop();
} else if (type == "ping" || cmd == "ping") {
this.ws.send({ cmd: "pong" });
}
};
this.ws.on("message", this.wsMessageHandler);
//
if (this.ws.socket && this.ws.socket.readyState === 1) {
this.sendSubscribe();
}
this.startWatchdog(); //
},
unLink(symbol) {
if (!this.ws || !this.ws.socket || this.ws.socket.readyState !== 1) return;
this.ws.send({ cmd: "unsub", msg: `swapBuyList_${symbol}` });
this.ws.send({ cmd: "unsub", msg: `swapSellList_${symbol}` });
this.ws.send({ cmd: "unsub", msg: `swapTradeList_${symbol}` });
}
// socket
linkSocket() {
if (this.ws.socket.readyState == 1) {
this.ws.send({
cmd: "sub",
msg: this.msg.buy
});
this.ws.send({
cmd: "sub",
msg: this.msg.sell
});
this.ws.send({
cmd: "sub",
msg: this.msg.trade
});
} else {
this.ws.on("open", () => {
this.ws.send({
cmd: "sub",
msg: this.msg.buy
});
this.ws.send({
cmd: "sub",
msg: this.msg.sell
});
this.ws.send({
cmd: "sub",
msg: this.msg.trade
});
});
}
this.ws.on("message", res => {
let { data, msg, code, sub, type, status, cmd } = res;
if (sub == this.msg.buy) {
this.buyList = data;
} else if (sub == this.msg.sell) {
this.sellList = data;
} else if (sub == this.msg.trade) {
// console.log('if (sub == this.msg.trade)', this.msg.trade)
this.tradeList.unshift(data);
this.tradeList.pop();
// this.newPriceObj = data;
// this.$emit("input", this.newPriceObj);
} else if (type == "ping" ||cmd == "ping") {
this.ws.send({
cmd: "pong"
});
}
});
// linkSocket() {
// if (this.ws.socket.readyState == 1) {
// this.ws.send({
// cmd: "sub",
// msg: this.msg.buy
// });
// this.ws.send({
// cmd: "sub",
// msg: this.msg.sell
// });
// this.ws.send({
// cmd: "sub",
// msg: this.msg.trade
// });
// } else {
// this.ws.on("open", () => {
// this.ws.send({
// cmd: "sub",
// msg: this.msg.buy
// });
// this.ws.send({
// cmd: "sub",
// msg: this.msg.sell
// });
// this.ws.send({
// cmd: "sub",
// msg: this.msg.trade
// });
// });
// }
// this.ws.on("message", res => {
// let { data, msg, code, sub, type, status, cmd } = res;
// if (sub == this.msg.buy) {
// this.buyList = data;
// } else if (sub == this.msg.sell) {
// this.sellList = data;
// } else if (sub == this.msg.trade) {
// // console.log('if (sub == this.msg.trade)', this.msg.trade)
// this.tradeList.unshift(data);
// this.tradeList.pop();
// // this.newPriceObj = data;
// // this.$emit("input", this.newPriceObj);
// } else if (type == "ping" ||cmd == "ping") {
// this.ws.send({
// cmd: "pong"
// });
// }
// });
},
//
unLink(symbol) {
// 线
this.ws.send({
cmd: "unsub",
msg: `swapBuyList_${symbol}`
});
// 线
this.ws.send({
cmd: "unsub",
msg: `swapSellList_${symbol}`
});
//
this.ws.send({
cmd: "unsub",
msg: `swapTradeList_${symbol}`
});
}
// },
// //
// unLink(symbol) {
// // 线
// this.ws.send({
// cmd: "unsub",
// msg: `swapBuyList_${symbol}`
// });
// // 线
// this.ws.send({
// cmd: "unsub",
// msg: `swapSellList_${symbol}`
// });
// //
// this.ws.send({
// cmd: "unsub",
// msg: `swapTradeList_${symbol}`
// });
// }
}
};
</script>

511
src/views/contract/index.vue

@ -164,6 +164,244 @@
</div>
</template>
<script>
// import kline from "../option/kline";
// import handicap from "./handicap.vue";
// import account from "./account.vue";
// import exchangeStore from "./exchange-store.vue";
// import pageBottom from "./page-bottom.vue";
// import Contract from "../../api/contract";
// import Socket from "@/api/server/Socket.js";
// import Home from "@/api/home";
// import bus from "@/components/bus.js";
// export default {
// components: {
// kline,
// handicap,
// account,
// exchangeStore,
// pageBottom
// },
// data() {
// return {
// contractList: [],
// activeSymbol: "",
// holdPositionAll: false,
// holdPositionList: [],
// newPriceObj: {},
// pcBannerList:[],
// accountInfo: {},
// defaultPrice: "",
// wsUrl: this.Globals.Server.Path.WS1,
// ws: new Socket(this.Globals.Server.Path.WS1),
// _time: null,
// contractOpen: false,
// contractAgreement: {},
// symbolDetail:{},
// currentIcon: '',
// imge:[],
// Liste:[],
// price1:0,
// intervalId:''
// };
// },
// computed: {
// activeContract(val) {
// let contractList=this.contractList
// .map(item => item.marketInfoList)
// .flat()
// .find(item => item.symbol == this.activeSymbol) || {}
// if(val.price){
// delete contractList.price
// }
// return contractList;
// },
// isLogin() {
// return Boolean(localStorage.token);
// }
// },
// watch: {
// activeSymbol() {
// this.holdPosition();
// },
// },
// destroyed() {
// clearInterval(this._time);
// },
// created() {
// // this.openStatus();
// this.getMarketList();
// this.holdPosition();
// this.indexList();
// this._time = setInterval(() => {
// if (this.contractOpen) {
// // mounted holdPosition
// this.holdPosition();
// }
// }, 3000);
// this.ws.on("open", () => {
// this.swapMarketList();
// });
// // console.info(this.$refs)
// bus.$on('collapse', msg => {
// this.activeContract.price =this.activeContract.symbol=='BTC'? (msg.close).toFixed(1):(msg.close).toFixed(3);
// this.holdPositionList.map(item=>{
// if(item.symbol==this.activeContract.symbol) item.realtimePrice=this.activeContract.price
// })
// });
// this.startWatchingPrice();
// },
// //
// mounted: function () {
// setInterval(() => {
// this.holdPosition();
// }, 2000)
// },
// methods: {
// startWatchingPrice(){
// this.intervalId = setInterval(() => {
// let newPrice = localStorage.getItem('price');
// this.price1 = newPrice;
// }, 10); //
// },
// ispopover1(item){
// this.activeSymbol=item;
// this.getMarketList();
// this.$refs.popover.showPopper = false;
// },
// swapMarketList() {
// let msg = "swapMarketList";
// this.ws.send({
// cmd: "sub",
// msg: msg
// });
// this.ws.on("message", res => {
// let { data, sub,cmd } = res;
// if (sub == msg) {
// // console.log(data, '11--------------------')
// if( data.symbol=='BTC' )(data.price).toFixed(1)
// this.contractList = data;
// // console.log(this.contractList);
// this.Listes();
// }else if (cmd == "ping") {
// this.ws.send({
// cmd: "pong"
// });
// }
// });
// this.ws.on('close',()=>{
// this.ws= new Socket(this.Globals.Server.Path.WS1),
// console.log('');
// this.wsOpen();
// })
// },
// Listes(){
// this.Liste = []
// this.contractList[0].marketInfoList.map(item=>{
// this.imge[0].marketInfoList.map(items=>{
// if(item.symbol==items.symbol){
// this.Liste.push({
// pair_name: item.pair_name,
// symbol: item.symbol,
// icon:items.icon
// })
// }
// })
// })
// },
// wsOpen(){
// this.ws.on("open", () => {
// this.swapMarketList();
// this.$refs.handicap.linkSocket()
// });
// },
// //
// getMarketList() {
// this.currentIcon = "";
// Contract.getMarketList().then(res => {
// if(this.activeSymbol==''){
// this.contractList = res;
// this.imge = res;
// //
// let firstParent = res[0];
// if (firstParent) {
// let first = firstParent.marketInfoList[0];
// if (first) this.activeSymbol = first.symbol;
// this.currentIcon = res[0].marketInfoList[0].icon;
// }
// }else{
// // icon
// // console.log('11111');
// for(let item of res[0].marketInfoList){
// if(this.activeSymbol==item.symbol){
// this.currentIcon = item.icon;
// }
// }
// }
// });
// },
// //
// holdPosition() {
// if (!this.isLogin) return;
// let data = {
// symbol: (this.holdPositionAll && this.activeSymbol) || ""
// };
// Contract.holdPosition(data, { loading: false }).then(res => {
// // console.info(res)
// res.map(item=>{
// if(item.symbol==this.activeContract.symbol) item.realtimePrice=this.activeContract.price
// })
// this.holdPositionList = res;
// });
// },
// //
// openStatus() {
// if(!this.isLogin) return;
// Contract.openStatus().then(res => {
// this.contractOpen = res.open;
// if (!this.contractOpen) {
// this.contractAgreement = res.contractAgreement;
// $("#openContract").modal("show");
// }
// });
// },
// //
// opening() {
// Contract.opening().then(res => {
// $("#openContract").modal("hide");
// this.contractOpen = true;
// this.$message.success(this.$t('contract.j9'));
// });
// },
// indexList() {
// Home.indexList().then((res) => {
// this.pcBannerList = res.pcBannerList
// // setTimeout(() => {
// // this.skroll();
// // }, 100);
// }).catch((res) => {});
// },
// //
// setactiveItem(index=0){
// this.accountInfo=this.holdPositionList[index]
// },
// // 线
// getLastHoldPosition(){
// let ti = 0,timer=null;
// timer = setInterval(()=>{
// this.holdPosition();
// ti++;
// if(ti==3){
// clearInterval(timer);
// }
// }, 1000)
// }
// }
// };
import kline from "../option/kline";
import handicap from "./handicap.vue";
import account from "./account.vue";
@ -173,6 +411,7 @@ import Contract from "../../api/contract";
import Socket from "@/api/server/Socket.js";
import Home from "@/api/home";
import bus from "@/components/bus.js";
export default {
components: {
kline,
@ -192,27 +431,35 @@ export default {
accountInfo: {},
defaultPrice: "",
wsUrl: this.Globals.Server.Path.WS1,
ws: new Socket(this.Globals.Server.Path.WS1),
// Socket
ws: null,
_time: null,
contractOpen: false,
contractAgreement: {},
symbolDetail:{},
currentIcon: '',
imge:[],
Liste:[],
price1:0,
intervalId:''
currentIcon: '',
imge:[],
Liste:[],
price1:0,
intervalId:'',
//
swapMarketHandler: null,
wsOpenHandler: null,
collapseHandler: null
};
},
computed: {
activeContract(val) {
let contractList=this.contractList
let contractList = this.contractList
.map(item => item.marketInfoList)
.flat()
.find(item => item.symbol == this.activeSymbol) || {}
if(val.price){
delete contractList.price
}
.find(item => item.symbol == this.activeSymbol) || {};
if(val.price){
delete contractList.price;
}
return contractList;
},
isLogin() {
@ -224,138 +471,164 @@ export default {
this.holdPosition();
},
},
destroyed() {
clearInterval(this._time);
},
created() {
// this.openStatus();
// Socket
this.ws = new Socket(this.wsUrl);
this.getMarketList();
this.holdPosition();
this.indexList();
this._time = setInterval(() => {
if (this.contractOpen) {
// mounted holdPosition
this.holdPosition();
}
}, 3000);
this.ws.on("open", () => {
this.swapMarketList();
});
// console.info(this.$refs)
bus.$on('collapse', msg => {
this.activeContract.price =this.activeContract.symbol=='BTC'? (msg.close).toFixed(1):(msg.close).toFixed(3);
this.holdPositionList.map(item=>{
if(item.symbol==this.activeContract.symbol) item.realtimePrice=this.activeContract.price
})
});
this.startWatchingPrice();
// websocket open
this.wsOpenHandler = () => {
console.log("主页面 WS 检测到连接/重连成功,请求市场列表...");
this.swapMarketList();
};
this.ws.on("open", this.wsOpenHandler);
// bus 线
this.collapseHandler = msg => {
this.activeContract.price = this.activeContract.symbol == 'BTC' ? (msg.close).toFixed(1) : (msg.close).toFixed(3);
this.holdPositionList.map(item => {
if (item.symbol == this.activeContract.symbol) item.realtimePrice = this.activeContract.price;
});
};
bus.$on('collapse', this.collapseHandler);
this.startWatchingPrice();
},
//
mounted: function () {
setInterval(() => {
this.holdPosition();
}, 2000)
// setInterval(() => {
// this.holdPosition();
// }, 2000);
},
//
beforeDestroy() {
clearInterval(this._time);
clearInterval(this.intervalId);
// Bus
if (this.collapseHandler) {
bus.$off('collapse', this.collapseHandler);
}
// websocket
if (this.ws) {
if (this.wsOpenHandler) this.ws.off("open", this.wsOpenHandler);
if (this.swapMarketHandler) this.ws.off("message", this.swapMarketHandler);
// ws
this.ws.send({ cmd: "unsub", msg: "swapMarketList" });
this.ws.destroy();
this.ws = null;
}
},
methods: {
startWatchingPrice(){
this.intervalId = setInterval(() => {
let newPrice = localStorage.getItem('price');
this.price1 = newPrice;
}, 10); //
},
ispopover1(item){
this.activeSymbol=item;
this.getMarketList();
startWatchingPrice() {
this.intervalId = setInterval(() => {
let newPrice = localStorage.getItem('price');
this.price1 = newPrice;
}, 10);
},
ispopover1(item) {
this.activeSymbol = item;
this.getMarketList();
this.$refs.popover.showPopper = false;
},
swapMarketList() {
let msg = "swapMarketList";
this.ws.send({
cmd: "sub",
msg: msg
});
this.ws.on("message", res => {
let { data, sub,cmd } = res;
// 1. open
if (this.ws && this.ws.checkOpen()) {
this.ws.send({ cmd: "sub", msg: msg });
}
// 2.
if (this.swapMarketHandler) {
this.ws.off("message", this.swapMarketHandler);
}
// 3.
this.swapMarketHandler = res => {
let { data, sub, cmd } = res;
if (sub == msg) {
// console.log(data, '11--------------------')
if( data.symbol=='BTC' )(data.price).toFixed(1)
if (data.symbol == 'BTC') (data.price).toFixed(1);
this.contractList = data;
console.log(this.contractList);
this.Listes();
}else if (cmd == "ping") {
this.ws.send({
cmd: "pong"
});
this.Listes();
} else if (cmd == "ping") {
this.ws.send({ cmd: "pong" });
}
});
this.ws.on('close',()=>{
this.ws= new Socket(this.Globals.Server.Path.WS1),
console.log('链接关闭');
this.wsOpen();
})
};
this.ws.on("message", this.swapMarketHandler);
},
Listes(){
this.Liste = []
this.contractList[0].marketInfoList.map(item=>{
this.imge[0].marketInfoList.map(items=>{
if(item.symbol==items.symbol){
this.Liste.push({
pair_name: item.pair_name,
symbol: item.symbol,
icon:items.icon
})
}
})
})
},
wsOpen(){
this.ws.on("open", () => {
this.swapMarketList();
this.$refs.handicap.linkSocket()
Listes() {
this.Liste = [];
if(!this.contractList || !this.contractList[0] || !this.imge[0]) return;
this.contractList[0].marketInfoList.map(item => {
this.imge[0].marketInfoList.map(items => {
if (item.symbol == items.symbol) {
this.Liste.push({
pair_name: item.pair_name,
symbol: item.symbol,
icon: items.icon
});
}
});
});
},
//
getMarketList() {
this.currentIcon = "";
this.currentIcon = "";
Contract.getMarketList().then(res => {
if(this.activeSymbol==''){
this.contractList = res;
this.imge = res;
//
let firstParent = res[0];
if (firstParent) {
let first = firstParent.marketInfoList[0];
if (first) this.activeSymbol = first.symbol;
this.currentIcon = res[0].marketInfoList[0].icon;
}
}else{
// icon
console.log('11111');
for(let item of res[0].marketInfoList){
if(this.activeSymbol==item.symbol){
this.currentIcon = item.icon;
}
}
}
if (this.activeSymbol == '') {
this.contractList = res;
this.imge = res;
let firstParent = res[0];
if (firstParent) {
let first = firstParent.marketInfoList[0];
if (first) this.activeSymbol = first.symbol;
this.currentIcon = res[0].marketInfoList[0].icon;
}
} else {
if(res && res[0]) {
for(let item of res[0].marketInfoList) {
if (this.activeSymbol == item.symbol) {
this.currentIcon = item.icon;
}
}
}
}
});
},
//
holdPosition() {
if (!this.isLogin) return;
let data = {
symbol: (this.holdPositionAll && this.activeSymbol) || ""
};
Contract.holdPosition(data, { loading: false }).then(res => {
// console.info(res)
res.map(item=>{
if(item.symbol==this.activeContract.symbol) item.realtimePrice=this.activeContract.price
})
res.map(item => {
if (item.symbol == this.activeContract.symbol) item.realtimePrice = this.activeContract.price;
});
this.holdPositionList = res;
});
},
//
openStatus() {
if(!this.isLogin) return;
Contract.openStatus().then(res => {
@ -366,7 +639,7 @@ export default {
}
});
},
//
opening() {
Contract.opening().then(res => {
$("#openContract").modal("hide");
@ -374,28 +647,26 @@ export default {
this.$message.success(this.$t('contract.j9'));
});
},
indexList() {
Home.indexList().then((res) => {
this.pcBannerList = res.pcBannerList
// setTimeout(() => {
// this.skroll();
// }, 100);
this.pcBannerList = res.pcBannerList;
}).catch((res) => {});
},
//
setactiveItem(index=0){
this.accountInfo=this.holdPositionList[index]
setactiveItem(index=0) {
this.accountInfo = this.holdPositionList[index];
},
// 线
getLastHoldPosition(){
let ti = 0,timer=null;
timer = setInterval(()=>{
getLastHoldPosition() {
let ti = 0, timer = null;
timer = setInterval(() => {
this.holdPosition();
ti++;
if(ti==3){
if (ti == 3) {
clearInterval(timer);
}
}, 1000)
}, 1000);
}
}
};

188
src/views/option/kline.vue

@ -129,60 +129,152 @@ data() {
isCreateSocket: false,
page: {},
tt:undefined,
periodCurrent: ''
periodCurrent: '',
//
wsOpenHandler: null,
wsMessageHandler: null,
// K线
lastMessageTime: 0,
watchdogTimer: null,
watchdogTimeout: 5000 // 5
};
},
// Socket
beforeDestroy() {
if (this.ws) {
this.stopWatchdog();
if (this.sub) this.unsub(this.ajaxTv.getSymbol(this.symbol), this.timer);
this.ws.destroy(); // destroy
this.ws = null;
}
},
methods: {
reconnect() {
if(this.isCreateSocket) {
return;
};
let msgObj = {
cmd: "sub",
msg: this.sub,
};
this.isCreateSocket = true;
//
this.tt && clearTimeout(this.tt);
let th=this
th.tt = setTimeout(function () {
th.isCreateSocket = false;
th.linkSocket(() => {
th.ws.send(msgObj);
});
// reconnect() {
// if(this.isCreateSocket) {
// return;
// };
// let msgObj = {
// cmd: "sub",
// msg: this.sub,
// };
// this.isCreateSocket = true;
// //
// this.tt && clearTimeout(this.tt);
// let th=this
// th.tt = setTimeout(function () {
// th.isCreateSocket = false;
// th.linkSocket(() => {
// th.ws.send(msgObj);
// });
}, 4000);
},
// socket
linkSocket(call) {
const ws = new Socket(this.wsUrl);
ws.on("open", () => {
this.ws = ws;
call && call();
});
// }, 4000);
// },
// // socket
// linkSocket(call) {
// const ws = new Socket(this.wsUrl);
// ws.on("open", () => {
// this.ws = ws;
// call && call();
// });
ws.on("message", (res) => {
let { data, msg, code, sub, type, status, req, cmd } = res;
if (sub == this.sub && this.onRealtimeCallback) {
if(sub.indexOf("BTC")!= -1) (data.close).toFixed(1)
this.onRealtimeCallback(this.getMap(data));
bus.$emit('collapse', data);
} else if (type == "ping" || cmd == "ping") {
this.ws.send({
cmd: "pong",
});
}
});
ws.on('close',()=>{
console.log('链接关闭');
this.reconnect();
})
ws.on('error',()=>{
console.log('发生异常了');
this.reconnect();
})
// ws.on("message", (res) => {
// let { data, msg, code, sub, type, status, req, cmd } = res;
// if (sub == this.sub && this.onRealtimeCallback) {
// if(sub.indexOf("BTC")!= -1) (data.close).toFixed(1)
// this.onRealtimeCallback(this.getMap(data));
// bus.$emit('collapse', data);
// } else if (type == "ping" || cmd == "ping") {
// this.ws.send({
// cmd: "pong",
// });
// }
// });
// ws.on('close',()=>{
// console.log('');
// this.reconnect();
// })
// ws.on('error',()=>{
// console.log('');
// this.reconnect();
// })
},
// },
// K线 15 WS
startWatchdog() {
this.stopWatchdog();
this.lastMessageTime = Date.now();
this.watchdogTimer = setInterval(() => {
if (Date.now() - this.lastMessageTime > this.watchdogTimeout) {
console.warn("[K线报警] 15秒没收到K线数据,强制重启底层WebSocket!");
if (this.ws) {
if (this.ws.socket) this.ws.socket.close();
this.ws.isReconnecting = false;
this.ws.manualClose = false;
this.ws.reconnect();
}
this.lastMessageTime = Date.now(); //
}
}, 5000);
},
stopWatchdog() {
if (this.watchdogTimer) {
clearInterval(this.watchdogTimer);
this.watchdogTimer = null;
}
},
// reconnect Socket.js
linkSocket(call) {
// WS
if (!this.ws) {
this.ws = new Socket(this.wsUrl);
// open线
this.ws.on("open", () => {
console.log("K线 WebSocket 连接/重连成功!");
//
if (call) {
call();
call = null; //
}
//
if (this.sub) {
this.ws.send({ cmd: "sub", msg: this.sub });
}
});
this.ws.on("message", (res) => {
let { data, sub, type, cmd } = res;
//
if (sub == this.sub || type == "ping" || cmd == "ping") {
this.lastMessageTime = Date.now();
}
if (sub == this.sub && this.onRealtimeCallback) {
if(sub.indexOf("BTC") != -1) (data.close).toFixed(1);
this.onRealtimeCallback(this.getMap(data));
bus.$emit('collapse', data);
} else if (type == "ping" || cmd == "ping") {
this.ws.send({ cmd: "pong" });
}
});
} else {
//
if (call) call();
if (this.ws.checkOpen() && this.sub) {
this.ws.send({ cmd: "sub", msg: this.sub });
}
}
this.startWatchdog(); //
},
//
unsub(pair_id, timer) {
let msgObj = {

Loading…
Cancel
Save