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

321
src/views/contract/handicap.vue

@ -140,6 +140,17 @@ export default {
buyList: [], buyList: [],
tradeList: [], tradeList: [],
newPriceObj: {}, newPriceObj: {},
//
wsOpenHandler: null,
wsMessageHandler: null,
collapseHandler: null,
//
isRetrying: false,
lastMessageTime: 0, //
watchdogTimer: null, //
watchdogTimeout: 5000 // 5
}; };
}, },
props: { props: {
@ -197,6 +208,7 @@ export default {
if (this.symbol) { if (this.symbol) {
this.getMarketInfo(); this.getMarketInfo();
this.linkSocket(); this.linkSocket();
this.startWatchdog();
} }
bus.$on('collapse', msg => { bus.$on('collapse', msg => {
this.newPriceObj.price =this.symbol=='BTC'? (msg.close).toFixed(1):(msg.close).toFixed(3); this.newPriceObj.price =this.symbol=='BTC'? (msg.close).toFixed(1):(msg.close).toFixed(3);
@ -215,26 +227,66 @@ export default {
}, },
beforeDestroy() { beforeDestroy() {
this.unLink(this.symbol); this.unLink(this.symbol);
this.removeSocketListeners();
this.stopWatchdog();
}, },
// //
methods: { methods: {
parseTime: date.parseTime, parseTime: date.parseTime,
omitTo: math.omitTo, omitTo: math.omitTo,
getMarketInfo() { // getMarketInfo() {
let data = { // let data = {
symbol: this.symbol // symbol: this.symbol
}; // };
Contract.getMarketInfo(data).then(res => { // Contract.getMarketInfo(data).then(res => {
this.sellList = res.swapSellList; // this.sellList = res.swapSellList;
this.buyList = res.swapBuyList; // this.buyList = res.swapBuyList;
this.tradeList = res.swapTradeList; // this.tradeList = res.swapTradeList;
// if(this.tradeList.length>0){ // // if(this.tradeList.length>0){
this.newPriceObj = this.tradeList[0]; // this.newPriceObj = this.tradeList[0];
// } // // }
this.$emit("input", this.newPriceObj); // this.$emit("input", this.newPriceObj);
localStorage.setItem("price",this.newPriceObj.price) // 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) { getValue(amount) {
const arr = this.buyListShow const arr = this.buyListShow
@ -243,75 +295,180 @@ export default {
let max = Math.max(...arr); let max = Math.max(...arr);
return math.division(amount, max, 2) * 100; 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 // socket
linkSocket() { // linkSocket() {
if (this.ws.socket.readyState == 1) { // if (this.ws.socket.readyState == 1) {
this.ws.send({ // this.ws.send({
cmd: "sub", // cmd: "sub",
msg: this.msg.buy // msg: this.msg.buy
}); // });
this.ws.send({ // this.ws.send({
cmd: "sub", // cmd: "sub",
msg: this.msg.sell // msg: this.msg.sell
}); // });
this.ws.send({ // this.ws.send({
cmd: "sub", // cmd: "sub",
msg: this.msg.trade // msg: this.msg.trade
}); // });
} else { // } else {
this.ws.on("open", () => { // this.ws.on("open", () => {
this.ws.send({ // this.ws.send({
cmd: "sub", // cmd: "sub",
msg: this.msg.buy // msg: this.msg.buy
}); // });
this.ws.send({ // this.ws.send({
cmd: "sub", // cmd: "sub",
msg: this.msg.sell // msg: this.msg.sell
}); // });
this.ws.send({ // this.ws.send({
cmd: "sub", // cmd: "sub",
msg: this.msg.trade // msg: this.msg.trade
}); // });
}); // });
} // }
this.ws.on("message", res => { // this.ws.on("message", res => {
let { data, msg, code, sub, type, status, cmd } = res; // let { data, msg, code, sub, type, status, cmd } = res;
if (sub == this.msg.buy) { // if (sub == this.msg.buy) {
this.buyList = data; // this.buyList = data;
} else if (sub == this.msg.sell) { // } else if (sub == this.msg.sell) {
this.sellList = data; // this.sellList = data;
} else if (sub == this.msg.trade) { // } else if (sub == this.msg.trade) {
// console.log('if (sub == this.msg.trade)', this.msg.trade) // // console.log('if (sub == this.msg.trade)', this.msg.trade)
this.tradeList.unshift(data); // this.tradeList.unshift(data);
this.tradeList.pop(); // this.tradeList.pop();
// this.newPriceObj = data; // // this.newPriceObj = data;
// this.$emit("input", this.newPriceObj); // // this.$emit("input", this.newPriceObj);
} else if (type == "ping" ||cmd == "ping") { // } else if (type == "ping" ||cmd == "ping") {
this.ws.send({ // this.ws.send({
cmd: "pong" // cmd: "pong"
}); // });
} // }
}); // });
}, // },
// // //
unLink(symbol) { // unLink(symbol) {
// 线 // // 线
this.ws.send({ // this.ws.send({
cmd: "unsub", // cmd: "unsub",
msg: `swapBuyList_${symbol}` // msg: `swapBuyList_${symbol}`
}); // });
// 线 // // 线
this.ws.send({ // this.ws.send({
cmd: "unsub", // cmd: "unsub",
msg: `swapSellList_${symbol}` // msg: `swapSellList_${symbol}`
}); // });
// // //
this.ws.send({ // this.ws.send({
cmd: "unsub", // cmd: "unsub",
msg: `swapTradeList_${symbol}` // msg: `swapTradeList_${symbol}`
}); // });
} // }
} }
}; };
</script> </script>

511
src/views/contract/index.vue

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

188
src/views/option/kline.vue

@ -129,60 +129,152 @@ data() {
isCreateSocket: false, isCreateSocket: false,
page: {}, page: {},
tt:undefined, 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: { methods: {
reconnect() { // reconnect() {
if(this.isCreateSocket) { // if(this.isCreateSocket) {
return; // return;
}; // };
let msgObj = { // let msgObj = {
cmd: "sub", // cmd: "sub",
msg: this.sub, // msg: this.sub,
}; // };
this.isCreateSocket = true; // this.isCreateSocket = true;
// // //
this.tt && clearTimeout(this.tt); // this.tt && clearTimeout(this.tt);
let th=this // let th=this
th.tt = setTimeout(function () { // th.tt = setTimeout(function () {
th.isCreateSocket = false; // th.isCreateSocket = false;
th.linkSocket(() => { // th.linkSocket(() => {
th.ws.send(msgObj); // th.ws.send(msgObj);
}); // });
}, 4000); // }, 4000);
}, // },
// socket // // socket
linkSocket(call) { // linkSocket(call) {
const ws = new Socket(this.wsUrl); // const ws = new Socket(this.wsUrl);
ws.on("open", () => { // ws.on("open", () => {
this.ws = ws; // this.ws = ws;
call && call(); // call && call();
}); // });
ws.on("message", (res) => { // ws.on("message", (res) => {
let { data, msg, code, sub, type, status, req, cmd } = res; // let { data, msg, code, sub, type, status, req, cmd } = res;
if (sub == this.sub && this.onRealtimeCallback) { // if (sub == this.sub && this.onRealtimeCallback) {
if(sub.indexOf("BTC")!= -1) (data.close).toFixed(1) // if(sub.indexOf("BTC")!= -1) (data.close).toFixed(1)
this.onRealtimeCallback(this.getMap(data)); // this.onRealtimeCallback(this.getMap(data));
bus.$emit('collapse', data); // bus.$emit('collapse', data);
} else if (type == "ping" || cmd == "ping") { // } else if (type == "ping" || cmd == "ping") {
this.ws.send({ // this.ws.send({
cmd: "pong", // cmd: "pong",
}); // });
} // }
}); // });
ws.on('close',()=>{ // ws.on('close',()=>{
console.log('链接关闭'); // console.log('');
this.reconnect(); // this.reconnect();
}) // })
ws.on('error',()=>{ // ws.on('error',()=>{
console.log('发生异常了'); // console.log('');
this.reconnect(); // 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) { unsub(pair_id, timer) {
let msgObj = { let msgObj = {

Loading…
Cancel
Save