Browse Source

对接tcp全部接口,行情数据页面的左右翻页

maziyang/feature-20251025172218-智能客服中台
hongxilin 4 weeks ago
parent
commit
8d9267d63b
  1. 230
      api/tcpConnection.js
  2. 307
      pages/marketSituation/globalIndex.vue
  3. 155
      pages/marketSituation/marketCondition.vue
  4. 340
      pages/marketSituation/marketDetail.vue
  5. 182
      pages/marketSituation/marketOverview.vue
  6. 55
      stores/modules/marketSituation.js

230
api/tcpConnection.js

@ -6,7 +6,7 @@
*/
// 引用TCP插件
const TCPSocket = uni.requireNativePlugin('Aimer-TCPPlugin');
const TCPSocket = uni.requireNativePlugin("Aimer-TCPPlugin");
// const TCPSocket = uni.requireNativePlugin("Aimer-TCPPlugin");
// TCP连接配置
@ -21,33 +21,33 @@ const TCP_CONFIG = {
* TCP连接管理类
*/
class TCPConnection {
constructor() {
this.channelConnections = new Map(); // 存储每个channel的连接状态
this.connectionCallbacks = [];
this.messageCallbacks = [];
}
constructor() {
this.channelConnections = new Map(); // 存储每个channel的连接状态
this.connectionCallbacks = [];
this.messageCallbacks = [];
}
/**
* TCP初始化连接
* @param {Object} config - 连接配置 {ip, port, channel, charsetname}
* @param {Function} callback - 连接状态回调函数
*/
connect(config = {}, callback = null) {
const channel = config.channel || TCP_CONFIG.channel;
/**
* TCP初始化连接
* @param {Object} config - 连接配置 {ip, port, channel, charsetname}
* @param {Function} callback - 连接状态回调函数
*/
connect(config = {}, callback = null) {
const channel = config.channel || TCP_CONFIG.channel;
// 如果该channel已经连接,先断开现有连接
if (this.channelConnections.get(channel)) {
console.log(`检测到channel ${channel}现有TCP连接,先断开...`);
this.disconnect(config);
// 等待断开完成后再连接
setTimeout(() => {
this._performConnect(config, callback);
}, 300);
} else {
// 直接连接
this._performConnect(config, callback);
}
// 如果该channel已经连接,先断开现有连接
if (this.channelConnections.get(channel)) {
console.log(`检测到channel ${channel}现有TCP连接,先断开...`);
this.disconnect(config);
// 等待断开完成后再连接
setTimeout(() => {
this._performConnect(config, callback);
}, 300);
} else {
// 直接连接
this._performConnect(config, callback);
}
}
/**
* 执行TCP连接
@ -66,33 +66,31 @@ class TCPConnection {
connectionConfig.charsetname = config.charsetname || TCP_CONFIG.charsetname;
}
console.log('开始建立TCP连接:', connectionConfig);
TCPSocket.connect(
connectionConfig,
result => {
/**
* status : 0 连接成功
* status : 1 断开连接
* receivedMsg : 服务器返回字符串(普通的字符串交互)
* receivedHexMsg : 服务器返回字节数组(单片机智能家居等硬件数据交互)
*/
if (result.status == '0') {
// TCP连接成功
this.channelConnections.set(connectionConfig.channel, true);
console.log(`TCP连接成功 - Channel ${connectionConfig.channel}`);
this._notifyConnectionCallbacks('connected', result, connectionConfig.channel);
} else if (result.status == '1') {
// TCP断开连接
this.channelConnections.set(connectionConfig.channel, false);
console.log(`TCP断开连接 - Channel ${connectionConfig.channel}`);
this._notifyConnectionCallbacks('disconnected', result, connectionConfig.channel);
}
console.log("开始建立TCP连接:", connectionConfig);
TCPSocket.connect(connectionConfig, (result) => {
/**
* status : 0 连接成功
* status : 1 断开连接
* receivedMsg : 服务器返回字符串(普通的字符串交互)
* receivedHexMsg : 服务器返回字节数组(单片机智能家居等硬件数据交互)
*/
if (result.status == "0") {
// TCP连接成功
this.channelConnections.set(connectionConfig.channel, true);
console.log(`TCP连接成功 - Channel ${connectionConfig.channel}`);
this._notifyConnectionCallbacks("connected", result, connectionConfig.channel);
} else if (result.status == "1") {
// TCP断开连接
this.channelConnections.set(connectionConfig.channel, false);
console.log(`TCP断开连接 - Channel ${connectionConfig.channel}`);
this._notifyConnectionCallbacks("disconnected", result, connectionConfig.channel);
}
if (result.receivedMsg) {
// 服务器返回字符串
console.log('收到字符串消息:', result.receivedMsg);
this._notifyMessageCallbacks('string', result.receivedMsg, null, connectionConfig.channel);
}
if (result.receivedMsg) {
// 服务器返回字符串
console.log("收到字符串消息:", result.receivedMsg);
this._notifyMessageCallbacks("string", result.receivedMsg, null, connectionConfig.channel);
}
// if (result.receivedHexMsg) {
// // 硬件服务器返回16进制数据
@ -115,18 +113,18 @@ class TCPConnection {
});
}
/**
* TCP发送消息(普通的字符串交互)
* @param {String|Object} message - 要发送的消息如果是对象会自动转换为JSON字符串
* @param {Object} config - 发送配置 {channel, charsetname}
*/
send(message, config = {}) {
const channel = config.channel || '1';
/**
* TCP发送消息(普通的字符串交互)
* @param {String|Object} message - 要发送的消息如果是对象会自动转换为JSON字符串
* @param {Object} config - 发送配置 {channel, charsetname}
*/
send(message, config = {}) {
const channel = config.channel || "1";
if (!this.channelConnections.get(channel)) {
console.warn(`TCP Channel ${channel}未连接,无法发送消息`);
return false;
}
if (!this.channelConnections.get(channel)) {
console.warn(`TCP Channel ${channel}未连接,无法发送消息`);
return false;
}
// 如果message是对象,转换为JSON字符串
let messageStr = message;
@ -149,20 +147,20 @@ class TCPConnection {
return true;
}
/**
* TCP断开连接
* @param {Object} config - 断开配置 {channel}
*/
disconnect(config = {}) {
const channel = config.channel || TCP_CONFIG.channel;
const disconnectConfig = {
channel: channel
};
/**
* TCP断开连接
* @param {Object} config - 断开配置 {channel}
*/
disconnect(config = {}) {
const channel = config.channel || TCP_CONFIG.channel;
const disconnectConfig = {
channel: channel,
};
TCPSocket.disconnect(disconnectConfig);
this.channelConnections.set(channel, false);
console.log(`TCP连接已断开 - Channel ${channel}`, disconnectConfig);
}
TCPSocket.disconnect(disconnectConfig);
this.channelConnections.set(channel, false);
console.log(`TCP连接已断开 - Channel ${channel}`, disconnectConfig);
}
/**
* 添加连接状态监听器
@ -206,50 +204,50 @@ class TCPConnection {
}
}
/**
* 获取连接状态
* @param {String} channel - 要检查的channel如果不指定则返回所有channel的连接状态
* @returns {Boolean|Object} 连接状态
*/
getConnectionStatus(channel = null) {
if (channel) {
return this.channelConnections.get(channel) || false;
}
// 返回所有channel的连接状态
const allConnections = {};
for (const [ch, status] of this.channelConnections) {
allConnections[ch] = status;
}
return allConnections;
/**
* 获取连接状态
* @param {String} channel - 要检查的channel如果不指定则返回所有channel的连接状态
* @returns {Boolean|Object} 连接状态
*/
getConnectionStatus(channel = null) {
if (channel) {
return this.channelConnections.get(channel) || false;
}
/**
* 通知连接状态回调
* @private
*/
_notifyConnectionCallbacks(status, result, channel) {
this.connectionCallbacks.forEach(callback => {
try {
callback(status, result, channel);
} catch (error) {
console.error('连接状态回调执行错误:', error);
}
});
// 返回所有channel的连接状态
const allConnections = {};
for (const [ch, status] of this.channelConnections) {
allConnections[ch] = status;
}
return allConnections;
}
/**
* 通知消息回调
* @private
*/
_notifyMessageCallbacks(type, message, parsedArray = null, channel = null) {
this.messageCallbacks.forEach(callback => {
try {
callback(type, message, parsedArray, channel);
} catch (error) {
console.error('消息回调执行错误:', error);
}
});
}
/**
* 通知连接状态回调
* @private
*/
_notifyConnectionCallbacks(status, result, channel) {
this.connectionCallbacks.forEach((callback) => {
try {
callback(status, result, channel);
} catch (error) {
console.error("连接状态回调执行错误:", error);
}
});
}
/**
* 通知消息回调
* @private
*/
_notifyMessageCallbacks(type, message, parsedArray = null, channel = null) {
this.messageCallbacks.forEach((callback) => {
try {
callback(type, message, parsedArray, channel);
} catch (error) {
console.error("消息回调执行错误:", error);
}
});
}
}
// 创建TCP连接实例

307
pages/marketSituation/globalIndex.vue

@ -32,7 +32,7 @@
<!-- 内容区域 -->
<scroll-view class="content" :style="{ top: contentTopPosition + 'px' }" scroll-y="true">
<!-- 亚太-中华 -->
<view class="market-section" v-for="item in globalIndexArray" :key="item">
<view class="market-section" v-for="(item, parentIndex) in marketSituationStore.gloablCardData" :key="item">
<view class="market-header">
<text class="market-title">{{ item.ac }}</text>
<view class="market-more" @click="viewMore(item.ac)">
@ -41,7 +41,7 @@
</view>
</view>
<view class="cards-grid-three">
<view v-for="iitem in item.list" :key="iitem" class="card-item">
<view v-for="(iitem, index) in item.list" :key="iitem" class="card-item">
<IndexCard
:market="iitem.market"
:stockName="iitem.name"
@ -49,7 +49,7 @@
:changeAmount="iitem.changeAmount"
:changePercent="iitem.changePercent"
:isRising="iitem.isRising"
@click="viewIndexDetail(iitem)"
@click="viewIndexDetail(iitem, parentIndex, index)"
/>
</view>
</view>
@ -65,11 +65,12 @@
</template>
<script setup>
import { ref, onMounted, computed, nextTick, watch } from "vue";
import { ref, onMounted, onUnmounted, computed, nextTick, watch } from "vue";
import footerBar from "../../components/footerBar.vue";
import IndexCard from "../../components/IndexCard.vue";
import { getRegionalGroupAPI } from "../../api/marketSituation/marketSituation.js";
import { useMarketSituationStore } from "../../stores/modules/marketSituation.js";
const marketSituationStore = useMarketSituationStore();
//
const iSMT = ref(0); //
const contentHeight = ref(0);
@ -259,7 +260,7 @@ const viewMore = (market) => {
};
//
const viewIndexDetail = (item) => {
const viewIndexDetail = (item, parentIndex, index) => {
console.log("查看指数详情:", item.stockName);
// uni.showToast({
// title: ` ${item.stockName} `,
@ -268,7 +269,7 @@ const viewIndexDetail = (item) => {
// })
//
uni.navigateTo({
url: `/pages/marketSituation/marketCondition?stockInformation=${encodeURIComponent(JSON.stringify(item))}`,
url: `/pages/marketSituation/marketCondition?stockInformation=${encodeURIComponent(JSON.stringify(item))}&parentIndex=${parentIndex}&index=${index}&from=globalIndex`,
});
};
@ -276,14 +277,306 @@ const getRegionalGroup = async () => {
try {
const result = await getRegionalGroupAPI();
globalIndexArray.value = result.data;
marketSituationStore.gloablCardData = result.data;
} catch (e) {
console.log("获取区域指数失败", e);
}
};
// TCP
import tcpConnection, { TCPConnection, TCP_CONFIG } from "@/api/tcpConnection.js";
const tcpConnected = ref(false);
const connectionListener = ref(null);
const messageListener = ref(null);
// TCP
const initTcpListeners = () => {
//
connectionListener.value = (status, result) => {
tcpConnected.value = status === "connected";
console.log("TCP连接状态变化:", status, tcpConnected.value);
//
//
if (status === "connected") {
sendTcpMessage("batch_real_time");
}
};
//
messageListener.value = (type, message, parsedArray) => {
const messageObj = {
type: type,
content: message,
parsedArray: parsedArray,
timestamp: new Date().toLocaleTimeString(),
direction: "received",
};
//
parseStockData(message);
};
//
tcpConnection.onConnectionChange(connectionListener.value);
tcpConnection.onMessage(messageListener.value);
};
// TCP
const connectTcp = () => {
console.log("开始连接TCP服务器...");
tcpConnection.connect();
};
// TCP
const disconnectTcp = () => {
console.log("断开TCP连接...");
tcpConnection.disconnect();
tcpConnected.value = false;
};
// TCP
const sendTcpMessage = (command) => {
let messageData;
let messageDataArray = [];
if (command == "batch_real_time") {
for (let i = 0; i < globalIndexArray.value.length; ++i) {
for (let j = 0; j < globalIndexArray.value[i].list.length; ++j) {
messageDataArray.push(globalIndexArray.value[i].list[j].code);
}
}
}
console.log(messageDataArray);
switch (command) {
//
case "real_time":
messageData = {
command: "real_time",
stock_code: "SH.000001",
};
break;
//
case "init_real_time":
messageData = {
command: "init_real_time",
stock_code: "SH.000001",
};
break;
case "stop_real_time":
messageData = {
command: "stop_real_time",
};
break;
//
case "stock_list":
messageData = {
command: "stock_list",
};
break;
case "batch_real_time":
messageData = {
command: "batch_real_time",
stock_codes: messageDataArray,
};
break;
case "help":
messageData = {
command: "help",
};
break;
}
if (!messageData) {
return;
} else {
try {
//
const success = tcpConnection.send(messageData);
if (success) {
console.log("home发送TCP消息:", messageData);
}
} catch (error) {
console.error("发送TCP消息时出错:", error);
}
}
};
// TCP
const getTcpStatus = () => {
const status = tcpConnection.getConnectionStatus();
uni.showModal({
title: "TCP连接状态",
content: `当前状态: ${status ? "已连接" : "未连接"}`,
showCancel: false,
});
};
let isMorePacket = {
init_batch_real_time: false,
batch_real_time: false,
};
let receivedMessage;
// TCP
const parseStockData = (message) => {
try {
console.log("进入parseStockData, message类型:", typeof message);
let parsedMessage;
// isMorePackettrue
// message{JSON
//
if (message.includes("欢迎连接到股票数据服务器")) {
console.log("服务器命令列表,不予处理");
return;
}
if ((typeof message === "string" && message.includes("batch_data_start")) || isMorePacket.init_batch_real_time) {
if (typeof message === "string" && message.includes("batch_data_start")) {
console.log("开始接受分包数据");
receivedMessage = "";
} else {
console.log("接收分包数据过程中");
}
isMorePacket.init_batch_real_time = true;
receivedMessage += message;
// }JSON
if (receivedMessage.includes("batch_data_complete")) {
console.log("接受分包数据结束");
isMorePacket.init_batch_real_time = false;
console.log("展示数据", receivedMessage);
let startIndex = 0;
let startCount = 0;
let endIndex = receivedMessage.indexOf("batch_data_complete");
for (let i = 0; i < receivedMessage.length; ++i) {
if (receivedMessage[i] == "{") {
startCount++;
if (startCount == 2) {
startIndex = i;
break;
}
}
}
for (let i = receivedMessage.indexOf("batch_data_complete"); i >= 0; --i) {
if (receivedMessage[i] == "}" || startIndex == endIndex) {
endIndex = i;
break;
}
}
if (startIndex >= endIndex) {
throw new Error("JSON字符串格式错误");
}
console.log("message", startIndex, endIndex, receivedMessage[endIndex], receivedMessage[startIndex]);
parsedMessage = JSON.parse(receivedMessage.substring(startIndex, endIndex + 1));
console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
const stockDataArray = parsedMessage.data;
for (let i = 0; i < globalIndexArray.value.length; ++i) {
for (let j = 0; j < globalIndexArray.value[i].list.length; ++j) {
const stockCode = globalIndexArray.value[i].list[j].code;
marketSituationStore.gloablCardData[i].list[j].currentPrice = stockDataArray[stockCode][0].current_price.toFixed(2);
marketSituationStore.gloablCardData[i].list[j].changeAmount = (stockDataArray[stockCode][0].current_price - stockDataArray[stockCode][0].pre_close).toFixed(2);
marketSituationStore.gloablCardData[i].list[j].changePercent = ((100 * (stockDataArray[stockCode][0].current_price - stockDataArray[stockCode][0].pre_close)) / stockDataArray[stockCode][0].pre_close).toFixed(2) + "%";
marketSituationStore.gloablCardData[i].list[j].isRising = stockDataArray[stockCode][0].current_price - stockDataArray[stockCode][0].pre_close >= 0;
}
}
}
} else if ((typeof message === "string" && message.includes('{"count')) || isMorePacket.batch_real_time) {
if (typeof message === "string" && message.includes('{"count')) {
console.log("开始接受分包数据");
receivedMessage = "";
} else {
console.log("接收分包数据过程中");
}
isMorePacket.batch_real_time = true;
receivedMessage += message;
// }JSON
if (receivedMessage.includes("batch_realtime_data")) {
console.log("接受分包数据结束");
isMorePacket.batch_real_time = false;
console.log("展示数据", receivedMessage);
let startIndex = 0;
let endIndex = receivedMessage.length - 1;
for (let i = 0; i < receivedMessage.length; ++i) {
if (receivedMessage[i] == "{") {
startIndex = i;
break;
}
}
for (let i = receivedMessage.length - 1; i >= 0; --i) {
if (receivedMessage[i] == "}" || startIndex == endIndex) {
endIndex = i;
break;
}
}
if (startIndex >= endIndex) {
throw new Error("JSON字符串格式错误");
}
parsedMessage = JSON.parse(receivedMessage.substring(startIndex, endIndex + 1));
console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
const stockDataArray = parsedMessage.data;
for (let i = 0; i < globalIndexArray.value.length; ++i) {
for (let j = 0; j < globalIndexArray.value[i].list.length; ++j) {
const stockCode = globalIndexArray.value[i].list[j].code;
marketSituationStore.gloablCardData[i].list[j].currentPrice = stockDataArray[stockCode][0].current_price.toFixed(2);
marketSituationStore.gloablCardData[i].list[j].changeAmount = (stockDataArray[stockCode][0].current_price - stockDataArray[stockCode][0].pre_close).toFixed(2);
marketSituationStore.gloablCardData[i].list[j].changePercent = ((100 * (stockDataArray[stockCode][0].current_price - stockDataArray[stockCode][0].pre_close)) / stockDataArray[stockCode][0].pre_close).toFixed(2) + "%";
marketSituationStore.gloablCardData[i].list[j].isRising = stockDataArray[stockCode][0].current_price - stockDataArray[stockCode][0].pre_close >= 0;
}
}
}
} else {
// JSON
console.log("不是需要的数据,不做处理");
}
} catch (error) {
console.error("解析TCP股票数据失败:", error.message);
console.error("错误详情:", error);
}
};
// TCP
const removeTcpListeners = () => {
if (connectionListener.value) {
tcpConnection.removeConnectionListener(connectionListener.value);
connectionListener.value = null;
console.log("已移除TCP连接状态监听器");
}
if (messageListener.value) {
tcpConnection.removeMessageListener(messageListener.value);
messageListener.value = null;
console.log("已移除TCP消息监听器");
}
};
const startTcp = () => {
try {
removeTcpListeners();
disconnectTcp();
initTcpListeners();
connectTcp();
} catch (error) {
console.error("建立连接并设置监听出错:", error);
}
};
onUnmounted(() => {
sendTcpMessage("stop_real_time");
removeTcpListeners();
disconnectTcp();
});
//
onMounted(async () => {
await getRegionalGroup();
initTcpListeners();
await nextTick();
//
startTcp();
//
const systemInfo = uni.getSystemInfoSync();
iSMT.value = systemInfo.statusBarHeight || 0;

155
pages/marketSituation/marketCondition.vue

@ -210,15 +210,15 @@
</view>
<view class="bottomTool">
<view class="index">
<view class="index" @click="goToIndexRepository">
<image class="icon" src="/static/marketSituation-image/marketCondition-image/index.png" mode="指标仓库图标"> </image>
指标仓库
</view>
<view class="function">
<view class="function" @click="goToFunction">
<image class="icon" src="/static/marketSituation-image/marketCondition-image/function.png" mode="功能图标"> </image>
功能
</view>
<view class="favorites">
<view class="favorites" @click="goToFavorites">
<image class="icon" src="/static/marketSituation-image/marketCondition-image/favorites.png" mode="加自选图标"></image>
加自选
</view>
@ -233,8 +233,9 @@ const instance = getCurrentInstance();
import { prevClosePrice, timeData as testTimeData, klineData as testKlineData } from "@/common/stockTimeInformation.js";
import { throttle } from "@/common/util.js";
import { HCharts } from "@/common/canvasMethod.js";
import tcpConnection, { TCPConnection, TCP_CONFIG } from "@/api/tcpConnection.js";
import tcpConnection, { TCPConnection, TCP_CONFIG } from "../../api/tcpConnection";
import { useMarketSituationStore } from "../../stores/modules/marketSituation.js";
const marketSituationStore = useMarketSituationStore();
// TCP
const tcpConnected = ref(false);
const connectionListener = ref(null);
@ -244,6 +245,7 @@ const messageListener = ref(null);
const currentStockFrom = ref();
//
const currentStockIndex = ref(-1);
const currentStockParentIndex = ref(-1);
//
const stockInformation = ref({
stockName: "----", //
@ -414,11 +416,6 @@ const startTcp = () => {
connectTcp();
} catch (error) {
console.error("建立连接并设置监听出错:", error);
uni.showToast({
title: "建立连接并设置监听",
icon: "none",
duration: 1500,
});
}
};
@ -516,25 +513,75 @@ const backToHomepage = () => {
};
const toLeftPage = () => {
if(currentStockFrom.value == "marketOverview"){
return;
}
if (currentStockIndex.value > 0) {
currentStockIndex.value--;
// updateStockInformation();
} else {
if (currentStockIndex.value == 0) {
uni.showToast({
title: "没有更多股票了",
icon: "none",
duration: 1000,
});
return;
} else {
currentStockIndex.value--;
let nextStockInformation;
if (currentStockFrom.value == "marketOverview") {
nextStockInformation = marketSituationStore.cardData[currentStockIndex.value];
} else if (currentStockFrom.value == "marketDetail") {
nextStockInformation = marketSituationStore.marketDetailCardData[currentStockIndex.value];
} else if (currentStockFrom.value == "globalIndex") {
nextStockInformation = marketSituationStore.gloablCardData[currentStockParentIndex.value].list[currentStockIndex.value];
} else {
uni.showToast({
title: "没有更多股票了",
icon: "none",
duration: 1000,
});
return;
}
updateStockInformation(nextStockInformation);
}
};
const toRightPage = () => {
if (currentStockIndex.value < stockList.length - 1) {
currentStockIndex.value++;
// updateStockInformation();
let nextStockInformation;
if (currentStockFrom.value == "marketOverview") {
if (currentStockIndex.value == marketSituationStore.cardData.length) {
uni.showToast({
title: "没有更多股票了",
icon: "none",
duration: 1000,
});
return;
} else {
currentStockIndex.value++;
nextStockInformation = marketSituationStore.cardData[currentStockIndex.value];
updateStockInformation(nextStockInformation);
}
} else if (currentStockFrom.value == "marketDetail") {
if (currentStockIndex.value == marketSituationStore.marketDetailCardData.length) {
uni.showToast({
title: "没有更多股票了",
icon: "none",
duration: 1000,
});
return;
} else {
currentStockIndex.value++;
nextStockInformation = marketSituationStore.marketDetailCardData[currentStockIndex.value];
updateStockInformation(nextStockInformation);
}
} else if (currentStockFrom.value == "globalIndex") {
if (currentStockIndex.value == marketSituationStore.gloablCardData[currentStockParentIndex.value].list.length) {
uni.showToast({
title: "没有更多股票了",
icon: "none",
duration: 1000,
});
return;
} else {
currentStockIndex.value++;
nextStockInformation = marketSituationStore.gloablCardData[currentStockParentIndex.value].list[currentStockIndex.value];
updateStockInformation(nextStockInformation);
}
} else {
uni.showToast({
title: "没有更多股票了",
@ -544,6 +591,38 @@ const toRightPage = () => {
}
};
const updateStockInformation = (stock) => {
klineTab.value = 1;
stockInformation.value.stockName = stock.stockName||stock.name;
stockInformation.value.stockCode = stock.stockCode||stock.code;
sendTcpMessage("stop_real_time");
sendTcpMessage("init_real_time");
};
const goToIndexRepository = () => {
uni.showToast({
title: "指标仓库",
icon: "none",
duration: 1000,
});
};
const goToFunction = () => {
uni.showToast({
title: "功能",
icon: "none",
duration: 1000,
});
};
const goToFavorites = () => {
uni.showToast({
title: "加自选",
icon: "none",
duration: 1000,
});
};
const openStockDetail = () => {
isStockDetail.value = true;
};
@ -1451,11 +1530,6 @@ const initTcpListeners = () => {
console.log("TCP连接状态变化:", status, tcpConnected.value);
//
uni.showToast({
title: status === "connected" ? "TCP连接成功" : "TCP连接断开",
icon: status === "connected" ? "success" : "none",
duration: 2000,
});
if (status === "connected") {
if (klineTab.value == 1) {
@ -1600,11 +1674,6 @@ const sendTcpMessage = (command) => {
break;
}
if (!messageData) {
uni.showToast({
title: "命令不存在",
icon: "none",
duration: 1000,
});
return;
} else {
try {
@ -1612,19 +1681,9 @@ const sendTcpMessage = (command) => {
const success = tcpConnection.send(messageData);
if (success) {
console.log("home发送TCP消息:", messageData);
uni.showToast({
title: "消息发送成功",
icon: "success",
duration: 1000,
});
}
} catch (error) {
console.error("发送TCP消息时出错:", error);
uni.showToast({
title: "消息发送失败",
icon: "none",
duration: 1000,
});
}
}
};
@ -2177,8 +2236,8 @@ onLoad((options) => {
// stockInformation
if (stockData) {
stockInformation.value.stockName = stockData.stockName;
stockInformation.value.stockCode = stockData.stockCode;
stockInformation.value.stockName = stockData.stockName||stockData.name;
stockInformation.value.stockCode = stockData.stockCode||stockData.code;
}
} catch (error) {
console.error("解析股票数据失败:", error);
@ -2193,9 +2252,17 @@ onLoad((options) => {
currentStockIndex.value = stockIndex;
}
// index
if (options.parentIndex) {
const stockParentIndex = parseInt(options.parentIndex);
console.log("股票在列表中的父索引:", stockParentIndex);
// index
currentStockParentIndex.value = stockParentIndex;
}
// stockFrom
if (options.stockFrom) {
currentStockFrom.value = options.stockFrom;
if (options.from) {
currentStockFrom.value = options.from;
}
});

340
pages/marketSituation/marketDetail.vue

@ -36,19 +36,19 @@
<scroll-view class="content" :style="{ top: contentTopPosition + 'px' }" scroll-y="true">
<!-- 股票列表 -->
<view class="stock-list">
<view class="stock-row" v-for="(stock, index) in sortedStockList" :key="index" @click="viewIndexDetail(stock)">
<view class="stock-row" v-for="(item,index) in sortedStockList" :key="item" @click="viewIndexDetail(item,index)">
<view class="stock-cell name-column">
<view class="stock-name">{{ stock.stockName }}</view>
<view class="stock-code">{{ stock.stockCode }}</view>
<view class="stock-name">{{ item.stockName }}</view>
<view class="stock-code">{{ item.stockCode }}</view>
</view>
<view class="stock-cell price-column">
<text class="stock-price" :class="stock.isRising ? 'rising' : 'falling'">
{{ typeof stock.price === "number" ? stock.price.toFixed(2) : stock.price }}
<text class="stock-price" :class="item.isRising ? 'rising' : 'falling'">
{{ typeof item.currentPrice === "number" ? item.currentPrice.toFixed(2) : item.currentPrice }}
</text>
</view>
<view class="stock-cell change-column">
<text class="stock-change" :class="stock.isRising ? 'rising' : 'falling'">
{{ stock.change || stock.changePercent }}
<text class="stock-change" :class="item.isRising ? 'rising' : 'falling'">
{{ item.changePercent }}
</text>
</view>
</view>
@ -64,10 +64,12 @@
</template>
<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import footerBar from "@/components/footerBar.vue";
import { getRegionalGroupListAPI } from "../../api/marketSituation/marketSituation.js";
import { useMarketSituationStore } from "../../stores/modules/marketSituation.js";
const marketSituationStore = useMarketSituationStore();
//
const iSMT = ref(0);
const contentHeight = ref(0);
@ -185,8 +187,8 @@ const contentTopPosition = computed(() => {
});
const sortedStockList = computed(() => {
console.log("计算sortedStockList,原始数据长度:", stockList.value.length);
let list = [...stockList.value];
console.log("计算sortedStockList,原始数据长度:", marketSituationStore.marketDetailCardData.length);
let list = [...marketSituationStore.marketDetailCardData];
if (sortType.value === "price") {
list.sort((a, b) => {
@ -194,8 +196,8 @@ const sortedStockList = computed(() => {
});
} else if (sortType.value === "change") {
list.sort((a, b) => {
const aChange = parseFloat(a.change.replace(/[+%-]/g, ""));
const bChange = parseFloat(b.change.replace(/[+%-]/g, ""));
const aChange = parseFloat(a.changePercent.replace(/[+%-]/g, ""));
const bChange = parseFloat(b.changePercent.replace(/[+%-]/g, ""));
return sortOrder.value === "asc" ? aChange - bChange : bChange - aChange;
});
}
@ -210,35 +212,23 @@ const getRegionalGroupList = async () => {
name: marketTitle.value,
});
regionalGroupArray.value = result.data;
marketSituationStore.marketDetailCardData = result.data;
} catch (e) {
console.error("获取区域分组列表失败:", e);
}
};
//
onLoad(async (options) => {
if (options && options.market) {
marketTitle.value = options.market;
await getRegionalGroupList();
}
});
//
const goBack = () => {
uni.navigateBack();
};
//
const viewIndexDetail = (item) => {
const viewIndexDetail = (item,index) => {
console.log("查看指数详情:", item.stockName);
// uni.showToast({
// title: ` ${item.stockName} `,
// icon: 'none',
// duration: 2000
// })
//
uni.navigateTo({
url: `/pages/marketSituation/marketCondition?stockInformation=${encodeURIComponent(JSON.stringify(item))}`,
url: `/pages/marketSituation/marketCondition?stockInformation=${encodeURIComponent(JSON.stringify(item))}&index=${index}&from=marketDetail`,
});
};
@ -260,6 +250,302 @@ const sortByChange = () => {
}
};
// TCP
import tcpConnection, { TCPConnection, TCP_CONFIG } from "@/api/tcpConnection.js";
const tcpConnected = ref(false);
const connectionListener = ref(null);
const messageListener = ref(null);
// TCP
const initTcpListeners = () => {
//
connectionListener.value = (status, result) => {
tcpConnected.value = status === "connected";
console.log("TCP连接状态变化:", status, tcpConnected.value);
//
if (status === "connected") {
sendTcpMessage("batch_real_time");
}
};
//
messageListener.value = (type, message, parsedArray) => {
const messageObj = {
type: type,
content: message,
parsedArray: parsedArray,
timestamp: new Date().toLocaleTimeString(),
direction: "received",
};
//
parseStockData(message);
};
//
tcpConnection.onConnectionChange(connectionListener.value);
tcpConnection.onMessage(messageListener.value);
};
// TCP
const connectTcp = () => {
console.log("开始连接TCP服务器...");
tcpConnection.connect();
};
// TCP
const disconnectTcp = () => {
console.log("断开TCP连接...");
tcpConnection.disconnect();
tcpConnected.value = false;
};
// TCP
const sendTcpMessage = (command) => {
let messageData;
let messageDataArray = [];
if (command == "batch_real_time") {
messageDataArray = regionalGroupArray.value.map((item) => item.code);
}
console.log(messageDataArray);
switch (command) {
//
case "real_time":
messageData = {
command: "real_time",
stock_code: "SH.000001",
};
break;
//
case "init_real_time":
messageData = {
command: "init_real_time",
stock_code: "SH.000001",
};
break;
case "stop_real_time":
messageData = {
command: "stop_real_time",
};
break;
//
case "stock_list":
messageData = {
command: "stock_list",
};
break;
case "batch_real_time":
messageData = {
command: "batch_real_time",
stock_codes: messageDataArray,
};
break;
case "help":
messageData = {
command: "help",
};
break;
}
if (!messageData) {
return;
} else {
try {
//
const success = tcpConnection.send(messageData);
if (success) {
console.log("home发送TCP消息:", messageData);
}
} catch (error) {
console.error("发送TCP消息时出错:", error);
}
}
};
// TCP
const getTcpStatus = () => {
const status = tcpConnection.getConnectionStatus();
uni.showModal({
title: "TCP连接状态",
content: `当前状态: ${status ? "已连接" : "未连接"}`,
showCancel: false,
});
};
let isMorePacket = {
init_batch_real_time: false,
batch_real_time: false,
};
let receivedMessage;
// TCP
const parseStockData = (message) => {
try {
console.log("进入parseStockData, message类型:", typeof message);
let parsedMessage;
// isMorePackettrue
// message{JSON
//
if (message.includes("欢迎连接到股票数据服务器")) {
console.log("服务器命令列表,不予处理");
return;
}
if ((typeof message === "string" && message.includes("batch_data_start")) || isMorePacket.init_batch_real_time) {
if (typeof message === "string" && message.includes("batch_data_start")) {
console.log("开始接受分包数据");
receivedMessage = "";
} else {
console.log("接收分包数据过程中");
}
isMorePacket.init_batch_real_time = true;
receivedMessage += message;
// }JSON
if (receivedMessage.includes("batch_data_complete")) {
console.log("接受分包数据结束");
isMorePacket.init_batch_real_time = false;
console.log("展示数据", receivedMessage);
let startIndex = 0;
let startCount = 0;
let endIndex = receivedMessage.indexOf("batch_data_complete");
for (let i = 0; i < receivedMessage.length; ++i) {
if (receivedMessage[i] == "{") {
startCount++;
if (startCount == 2) {
startIndex = i;
break;
}
}
}
for (let i = receivedMessage.indexOf("batch_data_complete"); i >= 0; --i) {
if (receivedMessage[i] == "}" || startIndex == endIndex) {
endIndex = i;
break;
}
}
if (startIndex >= endIndex) {
throw new Error("JSON字符串格式错误");
}
console.log("message", startIndex, endIndex, receivedMessage[endIndex], receivedMessage[startIndex]);
parsedMessage = JSON.parse(receivedMessage.substring(startIndex, endIndex + 1));
console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
const stockDataArray = parsedMessage.data;
marketSituationStore.marketDetailCardData = regionalGroupArray.value.map((item) => ({
market: item.market,
stockCode: item.code,
stockName: item.name,
id: item.id,
currentPrice: stockDataArray[item.code][0].current_price.toFixed(2),
changeAmount: (stockDataArray[item.code][0].current_price - stockDataArray[item.code][0].pre_close).toFixed(2),
changePercent: ((100 * (stockDataArray[item.code][0].current_price - stockDataArray[item.code][0].pre_close)) / stockDataArray[item.code][0].pre_close).toFixed(2) + "%",
isRising: stockDataArray[item.code][0].current_price - stockDataArray[item.code][0].pre_close >= 0,
}));
}
} else if ((typeof message === "string" && message.includes('{"count')) || isMorePacket.batch_real_time) {
if (typeof message === "string" && message.includes('{"count')) {
console.log("开始接受分包数据");
receivedMessage = "";
} else {
console.log("接收分包数据过程中");
}
isMorePacket.batch_real_time = true;
receivedMessage += message;
// }JSON
if (receivedMessage.includes("batch_realtime_data")) {
console.log("接受分包数据结束");
isMorePacket.batch_real_time = false;
console.log("展示数据", receivedMessage);
let startIndex = 0;
let endIndex = receivedMessage.length - 1;
for (let i = 0; i < receivedMessage.length; ++i) {
if (receivedMessage[i] == "{") {
startIndex = i;
break;
}
}
for (let i = receivedMessage.length - 1; i >= 0; --i) {
if (receivedMessage[i] == "}" || startIndex == endIndex) {
endIndex = i;
break;
}
}
if (startIndex >= endIndex) {
throw new Error("JSON字符串格式错误");
}
parsedMessage = JSON.parse(receivedMessage.substring(startIndex, endIndex + 1));
console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
const stockDataArray = parsedMessage.data;
marketSituationStore.marketDetailCardData = regionalGroupArray.value.map((item) => ({
market: item.market,
stockCode: item.code,
stockName: item.name,
id: item.id,
currentPrice: stockDataArray[item.code][0].current_price.toFixed(2),
changeAmount: (stockDataArray[item.code][0].current_price - stockDataArray[item.code][0].pre_close).toFixed(2),
changePercent: ((100 * (stockDataArray[item.code][0].current_price - stockDataArray[item.code][0].pre_close)) / stockDataArray[item.code][0].pre_close).toFixed(2) + "%",
isRising: stockDataArray[item.code][0].current_price - stockDataArray[item.code][0].pre_close >= 0,
}));
}
} else {
// JSON
console.log("不是需要的数据,不做处理");
}
} catch (error) {
console.error("解析TCP股票数据失败:", error.message);
console.error("错误详情:", error);
}
};
// TCP
const removeTcpListeners = () => {
if (connectionListener.value) {
tcpConnection.removeConnectionListener(connectionListener.value);
connectionListener.value = null;
console.log("已移除TCP连接状态监听器");
}
if (messageListener.value) {
tcpConnection.removeMessageListener(messageListener.value);
messageListener.value = null;
console.log("已移除TCP消息监听器");
}
};
const startTcp = () => {
try {
removeTcpListeners();
disconnectTcp();
initTcpListeners();
connectTcp();
} catch (error) {
console.error("建立连接并设置监听出错:", error);
}
};
//
onLoad(async (options) => {
if (options && options.market) {
marketTitle.value = options.market;
await getRegionalGroupList();
initTcpListeners();
await nextTick();
//
startTcp();
}
});
onUnmounted(() => {
sendTcpMessage("stop_real_time");
removeTcpListeners();
disconnectTcp();
});
onMounted(() => {
//
iSMT.value = uni.getSystemInfoSync().statusBarHeight;

182
pages/marketSituation/marketOverview.vue

@ -180,17 +180,9 @@ const initTcpListeners = () => {
tcpConnected.value = status === "connected";
console.log("TCP连接状态变化:", status, tcpConnected.value);
//
uni.showToast({
title: status === "connected" ? "TCP连接成功" : "TCP连接断开",
icon: status === "connected" ? "success" : "none",
duration: 2000,
});
//
if (status === "connected") {
if (klineTab.value == 1) {
sendTcpMessage("batch_real_time");
}
sendTcpMessage("batch_real_time");
}
};
@ -233,6 +225,7 @@ const sendTcpMessage = (command) => {
if (command == "batch_real_time") {
messageDataArray = globalIndexArray.value.map((item) => item.stockCode);
}
console.log(messageDataArray);
switch (command) {
//
@ -263,7 +256,7 @@ const sendTcpMessage = (command) => {
case "batch_real_time":
messageData = {
command: "batch_real_time",
stock_codes: ["SH.000001", "SH.000002"],
stock_codes: messageDataArray,
};
break;
case "help":
@ -273,11 +266,6 @@ const sendTcpMessage = (command) => {
break;
}
if (!messageData) {
uni.showToast({
title: "命令不存在",
icon: "none",
duration: 1000,
});
return;
} else {
try {
@ -285,19 +273,11 @@ const sendTcpMessage = (command) => {
const success = tcpConnection.send(messageData);
if (success) {
console.log("home发送TCP消息:", messageData);
uni.showToast({
title: "消息发送成功",
icon: "success",
duration: 1000,
});
}
} catch (error) {
console.error("发送TCP消息时出错:", error);
uni.showToast({
title: "消息发送失败",
icon: "none",
duration: 1000,
});
}
}
};
@ -313,41 +293,10 @@ const getTcpStatus = () => {
};
let isMorePacket = {
init_batch_real_time: false,
batch_real_time: false,
};
let receivedMessage;
const findJsonPacket = (message, command) => {
let jsonStartIndex = 0;
let jsonEndIndex = message.indexOf(command);
let jsonStartCount = 0;
let jsonEndCount = 0;
for (let i = 0; i < message.length - 1; ++i) {
if (message[i] == "{") {
jsonStartCount++;
if (jsonStartCount == 2) {
jsonStartIndex = i;
break;
}
}
}
for (let i = message.indexOf(command); i >= 0; --i) {
if (message[i] == "}" || i == jsonStartIndex) {
jsonEndCount++;
if (jsonEndCount == 1) {
jsonEndIndex = i;
break;
}
}
}
// JSON
if (jsonStartIndex >= jsonEndIndex) {
return { error: true };
}
return { json: JSON.parse(message.substring(jsonStartIndex, jsonEndIndex + 1)) };
};
// TCP
const parseStockData = (message) => {
@ -362,28 +311,105 @@ const parseStockData = (message) => {
console.log("服务器命令列表,不予处理");
return;
}
if (message.includes("real_time")) {
let startIndex = 0;
let endIndex = message.length;
for (let i = 0; i < message.length - 1; ++i) {
if (message[i] == "{") {
startIndex = i;
break;
if ((typeof message === "string" && message.includes("batch_data_start")) || isMorePacket.init_batch_real_time) {
if (typeof message === "string" && message.includes("batch_data_start")) {
console.log("开始接受分包数据");
receivedMessage = "";
} else {
console.log("接收分包数据过程中");
}
isMorePacket.init_batch_real_time = true;
receivedMessage += message;
// }JSON
if (receivedMessage.includes("batch_data_complete")) {
console.log("接受分包数据结束");
isMorePacket.init_batch_real_time = false;
console.log("展示数据", receivedMessage);
let startIndex = 0;
let startCount = 0;
let endIndex = receivedMessage.indexOf("batch_data_complete");
for (let i = 0; i < receivedMessage.length; ++i) {
if (receivedMessage[i] == "{") {
startCount++;
if (startCount == 2) {
startIndex = i;
break;
}
}
}
for (let i = receivedMessage.indexOf("batch_data_complete"); i >= 0; --i) {
if (receivedMessage[i] == "}" || startIndex == endIndex) {
endIndex = i;
break;
}
}
if (startIndex >= endIndex) {
throw new Error("JSON字符串格式错误");
}
console.log("message", startIndex, endIndex, receivedMessage[endIndex], receivedMessage[startIndex]);
parsedMessage = JSON.parse(receivedMessage.substring(startIndex, endIndex + 1));
console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
const stockDataArray = parsedMessage.data;
marketSituationStore.cardData = globalIndexArray.value.map((item) => ({
market: item.market,
stockCode: item.stockCode,
stockName: item.stockName,
currentPrice: stockDataArray[item.stockCode][0].current_price.toFixed(2),
changeAmount: (stockDataArray[item.stockCode][0].current_price - stockDataArray[item.stockCode][0].pre_close).toFixed(2),
changePercent: ((100 * (stockDataArray[item.stockCode][0].current_price - stockDataArray[item.stockCode][0].pre_close)) / stockDataArray[item.stockCode][0].pre_close).toFixed(2) + "%",
isRising: stockDataArray[item.stockCode][0].current_price - stockDataArray[item.stockCode][0].pre_close >= 0,
}));
}
} else if ((typeof message === "string" && message.includes('{"count')) || isMorePacket.batch_real_time) {
if (typeof message === "string" && message.includes('{"count')) {
console.log("开始接受分包数据");
receivedMessage = "";
} else {
console.log("接收分包数据过程中");
}
for (let i = message.length - 1; i >= 0; --i) {
if (message[i] == "}") {
endIndex = i;
break;
isMorePacket.batch_real_time = true;
receivedMessage += message;
// }JSON
if (receivedMessage.includes("batch_realtime_data")) {
console.log("接受分包数据结束");
isMorePacket.batch_real_time = false;
console.log("展示数据", receivedMessage);
let startIndex = 0;
let endIndex = receivedMessage.length - 1;
for (let i = 0; i < receivedMessage.length; ++i) {
if (receivedMessage[i] == "{") {
startIndex = i;
break;
}
}
for (let i = receivedMessage.length - 1; i >= 0; --i) {
if (receivedMessage[i] == "}" || startIndex == endIndex) {
endIndex = i;
break;
}
}
if (startIndex >= endIndex) {
throw new Error("JSON字符串格式错误");
}
parsedMessage = JSON.parse(receivedMessage.substring(startIndex, endIndex + 1));
console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
const stockDataArray = parsedMessage.data;
marketSituationStore.cardData = globalIndexArray.value.map((item) => ({
market: item.market,
stockCode: item.stockCode,
stockName: item.stockName,
currentPrice: stockDataArray[item.stockCode][0].current_price.toFixed(2),
changeAmount: (stockDataArray[item.stockCode][0].current_price - stockDataArray[item.stockCode][0].pre_close).toFixed(2),
changePercent: ((100 * (stockDataArray[item.stockCode][0].current_price - stockDataArray[item.stockCode][0].pre_close)) / stockDataArray[item.stockCode][0].pre_close).toFixed(2) + "%",
isRising: stockDataArray[item.stockCode][0].current_price - stockDataArray[item.stockCode][0].pre_close >= 0,
}));
}
parsedMessage = JSON.parse(message.substring(startIndex, endIndex + 1));
console.log("实时数据解析", parsedMessage);
return;
}else {
} else {
// JSON
console.log("不是需要的数据,不做处理");
}
@ -416,11 +442,7 @@ const startTcp = () => {
connectTcp();
} catch (error) {
console.error("建立连接并设置监听出错:", error);
uni.showToast({
title: "建立连接并设置监听",
icon: "none",
duration: 1500,
});
}
};

55
stores/modules/marketSituation.js

@ -6,57 +6,14 @@ import { ref } from "vue";
export const useMarketSituationStore = defineStore(
"marketSituation",
() => {
const cardData = ref([
{
market: "usa",
stockName: "道琼斯",
stockCode: "noCode",
currentPrice: "45757.90",
changeAmount: "-125.22",
changePercent: "-0.27%",
isRising: false,
},
{
market: "usa",
stockName: "纳斯达克",
stockCode: "noCode",
currentPrice: "22333.96",
changeAmount: "+125.22",
changePercent: "+0.47%",
isRising: true,
},
{
market: "usa",
stockName: "标普500",
stockCode: "noCode",
currentPrice: "6606.08",
changeAmount: "+125.22",
changePercent: "+0.27%",
isRising: true,
},
{
market: "cn",
stockName: "上证指数",
stockCode: "noCode",
currentPrice: "3333.96",
changeAmount: "+125.22",
changePercent: "+0.27%",
isRising: true,
},
{
market: "cn",
stockName: "科创50",
stockCode: "noCode",
currentPrice: "757.90",
changeAmount: "-25.22",
changePercent: "-0.27%",
isRising: false,
},
]);
const cardData = ref([]);
const gloablCardData = ref([]);
const marketDetailCardData = ref([]);
// 记得 return
return {
cardData
cardData,
gloablCardData,
marketDetailCardData,
};
},
// TODO: 持久化

Loading…
Cancel
Save