Browse Source

接入TCP

zhaowenkang/feature-20251028181547-行情页面
no99 4 weeks ago
parent
commit
2d61bf689c
  1. 4
      .hbuilderx/launch.json
  2. 411
      api/tcpConnection.js
  3. 22
      manifest.json
  4. 634
      pages/home/marketCondition.vue

4
.hbuilderx/launch.json

@ -2,8 +2,8 @@
"version" : "1.0",
"configurations" : [
{
"customPlaygroundType" : "device",
"playground" : "standard",
"customPlaygroundType" : "local",
"playground" : "custom",
"type" : "uni-app:app-android"
// "playground" : "standard",
// "type" : "uni-app:app-ios"

411
api/tcpConnection.js

@ -1,239 +1,238 @@
/**
* TCP连接工具类
* 用于处理TCP连接发送消息和断开连接
*
* @format
*/
// 引用TCP插件
const TCPSocket = uni.requireNativePlugin('Aimer-TCPPlugin');
const TCPSocket = uni.requireNativePlugin("Aimer-TCPPlugin");
// TCP连接配置
const TCP_CONFIG = {
ip: '192.168.1.9',
port: '8080',
channel: '1', // 可选 1~20
charsetname: 'UTF-8' // 默认UTF-8,可选GBK
ip: "192.168.1.9",
port: "8080",
channel: "1", // 可选 1~20
charsetname: "UTF-8", // 默认UTF-8,可选GBK
};
/**
* TCP连接管理类
*/
class TCPConnection {
constructor() {
this.isConnected = false;
this.connectionCallbacks = [];
this.messageCallbacks = [];
}
/**
* TCP初始化连接
* @param {Object} config - 连接配置 {ip, port, channel, charsetname}
* @param {Function} callback - 连接状态回调函数
*/
connect(config = {}, callback = null) {
// 如果已经连接,先断开现有连接
if (this.isConnected) {
console.log('检测到现有TCP连接,先断开...');
this.disconnect(config);
// 等待断开完成后再连接
setTimeout(() => {
this._performConnect(config, callback);
}, 300);
} else {
// 直接连接
this._performConnect(config, callback);
}
constructor() {
this.isConnected = false;
this.connectionCallbacks = [];
this.messageCallbacks = [];
}
/**
* TCP初始化连接
* @param {Object} config - 连接配置 {ip, port, channel, charsetname}
* @param {Function} callback - 连接状态回调函数
*/
connect(config = {}, callback = null) {
// 如果已经连接,先断开现有连接
if (this.isConnected) {
console.log("检测到现有TCP连接,先断开...");
this.disconnect(config);
// 等待断开完成后再连接
setTimeout(() => {
this._performConnect(config, callback);
}, 300);
} else {
// 直接连接
this._performConnect(config, callback);
}
/**
* 执行TCP连接
* @param {Object} config - 连接配置
* @param {Function} callback - 连接状态回调函数
*/
_performConnect(config = {}, callback = null) {
const connectionConfig = {
channel: config.channel || TCP_CONFIG.channel,
ip: config.ip || TCP_CONFIG.ip,
port: config.port || TCP_CONFIG.port
};
// 如果指定了字符集,添加到配置中
if (config.charsetname || TCP_CONFIG.charsetname) {
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.isConnected = true;
console.log('TCP连接成功');
this._notifyConnectionCallbacks('connected', result);
} else if (result.status == '1') {
// TCP断开连接
this.isConnected = false;
console.log('TCP断开连接');
this._notifyConnectionCallbacks('disconnected', result);
}
if (result.receivedMsg) {
// 服务器返回字符串
console.log('收到字符串消息:', result.receivedMsg);
this._notifyMessageCallbacks('string', result.receivedMsg);
}
// if (result.receivedHexMsg) {
// // 硬件服务器返回16进制数据
// console.log('收到16进制消息:', result.receivedHexMsg);
// let msg = result.receivedHexMsg;
// let sum = msg.length / 2;
// let arr = [];
// for (let k = 0; k < sum; k++) {
// let i = msg.substring(k * 2, k * 2 + 2);
// arr.push(i);
// }
// console.log('解析后的16进制数组:', arr);
// this._notifyMessageCallbacks('hex', result.receivedHexMsg, arr);
// }
// 执行回调函数
if (callback && typeof callback === 'function') {
callback(result);
}
}
);
}
/**
* TCP发送消息(普通的字符串交互)
* @param {String|Object} message - 要发送的消息如果是对象会自动转换为JSON字符串
* @param {Object} config - 发送配置 {channel, charsetname}
*/
send(message, config = {}) {
if (!this.isConnected) {
console.warn('TCP未连接,无法发送消息');
return false;
}
// 如果message是对象,转换为JSON字符串
let messageStr = message;
if (typeof message === 'object') {
messageStr = JSON.stringify(message) + '\n';
}
const sendConfig = {
channel: config.channel || '1', // 注意:channel应该是字符串
message: messageStr
};
// 如果指定了字符编码,添加到配置中
if (config.charsetname) {
sendConfig.charsetname = config.charsetname;
}
TCPSocket.send(sendConfig);
console.log('js成功发送TCP消息:', messageStr);
return true;
}
/**
* 执行TCP连接
* @param {Object} config - 连接配置
* @param {Function} callback - 连接状态回调函数
*/
_performConnect(config = {}, callback = null) {
const connectionConfig = {
channel: config.channel || TCP_CONFIG.channel,
ip: config.ip || TCP_CONFIG.ip,
port: config.port || TCP_CONFIG.port,
};
// 如果指定了字符集,添加到配置中
if (config.charsetname || TCP_CONFIG.charsetname) {
connectionConfig.charsetname = config.charsetname || TCP_CONFIG.charsetname;
}
/**
* TCP断开连接
* @param {Object} config - 断开配置 {channel}
*/
disconnect(config = {}) {
const disconnectConfig = {
channel: config.channel || TCP_CONFIG.channel
};
TCPSocket.disconnect(disconnectConfig);
console.log("开始建立TCP连接:", connectionConfig);
TCPSocket.connect(connectionConfig, (result) => {
/**
* status : 0 连接成功
* status : 1 断开连接
* receivedMsg : 服务器返回字符串(普通的字符串交互)
* receivedHexMsg : 服务器返回字节数组(单片机智能家居等硬件数据交互)
*/
if (result.status == "0") {
// TCP连接成功
this.isConnected = true;
console.log("TCP连接成功");
this._notifyConnectionCallbacks("connected", result);
} else if (result.status == "1") {
// TCP断开连接
this.isConnected = false;
console.log('TCP连接已断开', disconnectConfig);
console.log("TCP断开连接");
this._notifyConnectionCallbacks("disconnected", result);
}
if (result.receivedMsg) {
// 服务器返回字符串
console.log("收到字符串消息:", result.receivedMsg);
this._notifyMessageCallbacks("string", result.receivedMsg);
}
// if (result.receivedHexMsg) {
// // 硬件服务器返回16进制数据
// console.log('收到16进制消息:', result.receivedHexMsg);
// let msg = result.receivedHexMsg;
// let sum = msg.length / 2;
// let arr = [];
// for (let k = 0; k < sum; k++) {
// let i = msg.substring(k * 2, k * 2 + 2);
// arr.push(i);
// }
// console.log('解析后的16进制数组:', arr);
// this._notifyMessageCallbacks('hex', result.receivedHexMsg, arr);
// }
// 执行回调函数
if (callback && typeof callback === "function") {
callback(result);
}
});
}
/**
* TCP发送消息(普通的字符串交互)
* @param {String|Object} message - 要发送的消息如果是对象会自动转换为JSON字符串
* @param {Object} config - 发送配置 {channel, charsetname}
*/
send(message, config = {}) {
if (!this.isConnected) {
console.warn("TCP未连接,无法发送消息");
return false;
}
/**
* 添加连接状态监听器
* @param {Function} callback - 回调函数 (status, result) => {}
*/
onConnectionChange(callback) {
if (typeof callback === 'function') {
this.connectionCallbacks.push(callback);
}
// 如果message是对象,转换为JSON字符串
let messageStr = message;
if (typeof message === "object") {
messageStr = JSON.stringify(message) + "\n";
}
/**
* 添加消息监听器
* @param {Function} callback - 回调函数 (type, message, parsedArray) => {}
*/
onMessage(callback) {
if (typeof callback === 'function') {
this.messageCallbacks.push(callback);
}
}
const sendConfig = {
channel: config.channel || "1", // 注意:channel应该是字符串
message: messageStr,
};
/**
* 移除连接状态监听器
* @param {Function} callback - 要移除的回调函数
*/
removeConnectionListener(callback) {
const index = this.connectionCallbacks.indexOf(callback);
if (index > -1) {
this.connectionCallbacks.splice(index, 1);
}
// 如果指定了字符编码,添加到配置中
if (config.charsetname) {
sendConfig.charsetname = config.charsetname;
}
/**
* 移除消息监听器
* @param {Function} callback - 要移除的回调函数
*/
removeMessageListener(callback) {
const index = this.messageCallbacks.indexOf(callback);
if (index > -1) {
this.messageCallbacks.splice(index, 1);
}
TCPSocket.send(sendConfig);
console.log("js成功发送TCP消息:", messageStr);
return true;
}
/**
* TCP断开连接
* @param {Object} config - 断开配置 {channel}
*/
disconnect(config = {}) {
const disconnectConfig = {
channel: config.channel || TCP_CONFIG.channel,
};
TCPSocket.disconnect(disconnectConfig);
this.isConnected = false;
console.log("TCP连接已断开", disconnectConfig);
}
/**
* 添加连接状态监听器
* @param {Function} callback - 回调函数 (status, result) => {}
*/
onConnectionChange(callback) {
if (typeof callback === "function") {
this.connectionCallbacks.push(callback);
}
/**
* 获取连接状态
* @returns {Boolean} 连接状态
*/
getConnectionStatus() {
return this.isConnected;
}
/**
* 添加消息监听器
* @param {Function} callback - 回调函数 (type, message, parsedArray) => {}
*/
onMessage(callback) {
if (typeof callback === "function") {
this.messageCallbacks.push(callback);
}
/**
* 通知连接状态回调
* @private
*/
_notifyConnectionCallbacks(status, result) {
this.connectionCallbacks.forEach(callback => {
try {
callback(status, result);
} catch (error) {
console.error('连接状态回调执行错误:', error);
}
});
}
/**
* 移除连接状态监听器
* @param {Function} callback - 要移除的回调函数
*/
removeConnectionListener(callback) {
const index = this.connectionCallbacks.indexOf(callback);
if (index > -1) {
this.connectionCallbacks.splice(index, 1);
}
/**
* 通知消息回调
* @private
*/
_notifyMessageCallbacks(type, message, parsedArray = null) {
this.messageCallbacks.forEach(callback => {
try {
callback(type, message, parsedArray);
} catch (error) {
console.error('消息回调执行错误:', error);
}
});
}
/**
* 移除消息监听器
* @param {Function} callback - 要移除的回调函数
*/
removeMessageListener(callback) {
const index = this.messageCallbacks.indexOf(callback);
if (index > -1) {
this.messageCallbacks.splice(index, 1);
}
}
/**
* 获取连接状态
* @returns {Boolean} 连接状态
*/
getConnectionStatus() {
return this.isConnected;
}
/**
* 通知连接状态回调
* @private
*/
_notifyConnectionCallbacks(status, result) {
this.connectionCallbacks.forEach((callback) => {
try {
callback(status, result);
} catch (error) {
console.error("连接状态回调执行错误:", error);
}
});
}
/**
* 通知消息回调
* @private
*/
_notifyMessageCallbacks(type, message, parsedArray = null) {
this.messageCallbacks.forEach((callback) => {
try {
callback(type, message, parsedArray);
} catch (error) {
console.error("消息回调执行错误:", error);
}
});
}
}
// 创建TCP连接实例

22
manifest.json

@ -1,6 +1,6 @@
{
"name" : "DeepChartApp",
"appid" : "__UNI__D8DF433",
"appid" : "__UNI__9C9AB28",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : "100",
@ -42,7 +42,9 @@
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
"ios" : {},
"ios" : {
"dSYMs" : false
},
/* ios */
"sdkConfigs" : {
"oauth" : {
@ -52,6 +54,22 @@
}
}
}
},
"nativePlugins" : {
"Aimer-TCPPlugin" : {
"__plugin_info__" : {
"name" : "TCP-Socket原生插件(支持Android和IOS) - [试用版,仅用于自定义调试基座]",
"description" : "Uniapp实现基于TCP的数据通信,支持单片机、智能家居等硬件交互,联系QQ: 462108858",
"platforms" : "Android,iOS",
"url" : "https://ext.dcloud.net.cn/plugin?id=2029",
"android_package_name" : "",
"ios_bundle_id" : "",
"isCloud" : true,
"bought" : 0,
"pid" : "2029",
"parameters" : {}
}
}
}
},
/* SDK */

634
pages/home/marketCondition.vue

@ -15,8 +15,8 @@
</view>
<view class="arrow-right"> </view>
</view>
<image class="search" src="/static/marketSituation-image/search.png" mode="搜索" @click="startTcp()"> </image>
<view class="more" @click="disconnect()">···</view>
<image class="search" src="/static/marketSituation-image/search.png" mode="搜索" @click="search()"> </image>
<view class="more" @click="getMore()">···</view>
</view>
</view>
@ -196,8 +196,14 @@
</view>
<!-- K线图区域 -->
<view class="test" v-else-if="klineTab === 3">
<button @click="sendGetTimeData()">接收消息</button>
<button @click="startTcp()">接收消息</button>
<button @click="sendStopTimeData()">停止消息</button>
<button @click="sendTcpMessage('real_time')">实时行情推送</button>
<button @click="sendTcpMessage('init_real_time')">初始化获取行情历史数据</button>
<button @click="sendTcpMessage('stop_real_time')">停止实时推送</button>
<view class="tcpMsg" v-for="item in tcpMessages" :key="item">
{{ item }}
</view>
</view>
<view v-else class="kline-chart-container">
<text>K线图开发中...</text>
@ -230,15 +236,27 @@ 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";
// const TCPSocket = uni.requireNativePlugin("Aimer-TCPPlugin");
const tcpObject = {
ip: "192.168.1.9",
port: 8080,
reconnectInterval: 3000,
isConnected: false,
};
const TIME_OUT = 1000 * 5;
const resultR = ref([]);
import tcpConnection, { TCPConnection, TCP_CONFIG } from "@/api/tcpConnection.js";
// TCP
const tcpConnected = ref(false);
const tcpMessages = ref([]);
const tcpStockData = ref({
count: 0,
data: {},
stock_count: 0,
timestamp: "",
type: "",
});
const currentStockInfo = ref({
stock_name: "未知股票",
current_price: "0.00",
change: "0.00%",
change_value: 0,
change_percent: 0,
});
const connectionListener = ref(null);
const messageListener = ref(null);
//
const stockInformation = ref({
@ -401,29 +419,26 @@ const moreTabsData = ref([
// K线Tab
// 1: 2:K 3:K 4:K
const klineTab = ref(2);
const sendGetTimeData = () => {
console.log("执行发送消息的方法");
const klineTab = ref(1);
const startTcp = () => {
try {
TCPSocket.send({
channel: "1",
message: '{"command": "real_time", "stock_code": "SH.000001"}',
removeTcpListeners();
disconnectTcp();
initTcpListeners();
connectTcp();
} catch (error) {
console.error("建立连接并设置监听:", error);
uni.showToast({
title: "建立连接并设置监听",
icon: "none",
duration: 1500,
});
} catch (e) {
console.log("error", e);
}
};
const sendStopTimeData = () => {
try {
TCPSocket.send({
channel: "1",
message: '{"command": "stop_real_time"}',
});
} catch (e) {
console.log("error", e);
}
disconnectTcp();
removeTcpListeners();
};
//
@ -450,9 +465,11 @@ const confirmStockColor = (price, lastDayStockClosePrice) => {
// K线
const selectKlineTab = (tabId) => {
klineTab.value = tabId;
if (tabId === 1) {
stockInformation.value.lastDayStockClosePrice = prevClosePrice;
if (klineTab.value == 1) {
sendTcpMessage("init_real_time");
}
initCanvas();
// startAddDataTimer();
};
@ -929,6 +946,7 @@ const drawChart = () => {
//
if (klineTab.value == 1) {
console.log("stockInfomaton.lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
//
const label = [
{
@ -1364,151 +1382,341 @@ watch(klineTab, () => {
console.log("标签页变化");
drawChart();
});
/*
const connectTcp = (ip, port) => {
console.log(`🚀 正在连接TCP服务器 ${ip}:${port}...`);
TCPSocket.connect(
{
channel: "1",
ip: ip,
port: port,
},
(result) => {
console.log(result);
if (result.status == 0) {
tcpObject.isConnected = true;
console.log("tcp连接成功");
} else if (result.status == 1) {
tcpObject.isConnected = false;
console.log("tcp断开连接");
}
if (result.receivedMsg) {
console.log("收到服务器发送的数据", result.receivedMsg);
if (result.receivedMsg.length == 0 || result.receivedMsg.includes("欢迎")) {
resultR.value = [];
} else {
const msgPacket = JSON.parse(result.receivedMsg);
resultR.value.push(msgPacket);
//
if (msgPacket.stock_code) {
stockInformation.value.stockCode = msgPacket.stock_code;
}
//
if (msgPacket.stock_name) {
stockInformation.value.stockName = msgPacket.stock_name;
}
//
if (msgPacket.pre_close) {
stockInformation.value.lastDayStockClosePrice = msgPacket.pre_close;
}
//
if (msgPacket.current_price) {
stockInformation.value.currentPrice = msgPacket.current_price;
}
//
if (msgPacket.current_price && msgPacket.pre_close) {
stockInformation.value.currentValue = msgPacket.current_price - msgPacket.pre_close;
stockInformation.value.currentRatio = ((msgPacket.current_price - msgPacket.pre_close) / msgPacket.pre_close) * 100;
}
//
if (msgPacket.high_price) {
stockInformation.value.highPrice = msgPacket.high_price;
}
//
if (msgPacket.close_price) {
stockInformation.value.lowPrice = msgPacket.close_price;
}
//
if (msgPacket.open_price) {
stockInformation.value.openPrice = msgPacket.open_price;
}
//
if (msgPacket.low_price) {
stockInformation.value.lowPrice = msgPacket.low_price;
}
//
if (msgPacket.current_price) {
stockInformation.value.closePrice = msgPacket.current_price;
}
//
if (msgPacket.volume) {
stockInformation.value.volume = msgPacket.volume;
}
//
if (msgPacket.volume_ratio) {
stockInformation.value.volumeRatio = msgPacket.volume_ratio;
}
//
if (msgPacket.amount) {
stockInformation.value.amount = msgPacket.amount;
}
//
if (msgPacket.market_earn) {
stockInformation.value.marketEarn = msgPacket.market_earn;
}
//
if (msgPacket.turnover_ratio) {
stockInformation.value.turnoverRatio = msgPacket.turnover_ratio;
}
//
if (msgPacket.total_market_value) {
stockInformation.value.marketValue = msgPacket.total_market_value;
}
}
}
// if (result.receivedHexMsg) {
// //16
// console.log("📥 16:", result.receivedHexMsg);
// let msg = result.receivedHexMsg;
// let sum = msg.length / 2;
// let arr = [];
// for (let k = 0; k < sum; k++) {
// let i = msg.substring(k * 2, k * 2 + 2);
// arr.push(i);
// }
// console.log("16:", arr);
// if (tcpObject.responseCallback) {
// tcpObject.responseCallback({
// data: arr,
// });
// }
// }
//
setTimeout(() => {
if (!tcpObject.isConnected) {
throw new Error("连接超时");
return;
}
}, TIME_OUT);
}
);
};
//
const disconnect = () => {
try {
TCPSocket.disconnect({
channel: "1",
});
tcpObject.isConnected = false;
console.log("✅ 连接已关闭");
} catch (e) {
console.log("⚠️ 断开连接时发生错误:", e.message);
}
};
const startTcp = async () => {
console.log("🚀 TCP客户端启动");
console.log(`目标服务器: ${tcpObject.ip}:${tcpObject.port}`);
try {
//
await connectTcp(tcpObject.ip, tcpObject.port);
} catch (e) {
console.log("error", e);
}
};
*/
// TCP
const initTcpListeners = () => {
//
connectionListener.value = (status, result) => {
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("init_real_time");
}
}
};
//
messageListener.value = (type, message, parsedArray) => {
const messageObj = {
type: type,
content: message,
parsedArray: parsedArray,
timestamp: new Date().toLocaleTimeString(),
direction: "received",
};
console.log("0000");
tcpMessages.value.push(messageObj);
// console.log('TCP:', messageObj)
console.log("home开始调用parseStockData", messageObj);
//
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;
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 "daily_data":
messageData = {
command: "daily_data",
stock_code: "GBPAUD.FXCM",
start_date: "20251001",
end_date: "20251023",
};
break;
case "weekly_data":
messageData = {
command: "weekly_data",
stock_code: "000001.SZ",
start_date: "20251001",
end_date: "20251023",
};
break;
case "daily_one_minutes_data":
messageData = {
command: "daily_one_minutes_data",
stock_code: "000001.SZ",
};
break;
case "daily_five_minutes_data":
messageData = {
command: "daily_five_minutes_data",
stock_code: "000001.SZ",
};
break;
case "daily_fifteen_minutes_data":
messageData = {
command: "daily_fifteen_minutes_data",
stock_code: "000001.SZ",
};
break;
case "daily_thirty_minutes_data":
messageData = {
command: "daily_thirty_minutes_data",
stock_code: "000001.SZ",
};
break;
case "daily_sixty_minutes_data":
messageData = {
command: "daily_sixty_minutes_data",
stock_code: "000001.SZ",
};
break;
case "batch_real_time":
messageData = {
command: "batch_real_time",
stock_codes: ["SH.000001", "SH.000002", "SH.000003", "SH.000004", "SH.000005"],
};
break;
case "help":
messageData = {
command: "help",
};
break;
}
if (!messageData) {
uni.showToast({
title: "命令不存在",
icon: "none",
duration: 1500,
});
return;
} else {
try {
//
const success = tcpConnection.send(messageData);
if (success) {
console.log("home发送TCP消息:", messageData);
uni.showToast({
title: "消息发送成功",
icon: "success",
duration: 1500,
});
}
} catch (error) {
console.error("发送TCP消息时出错:", error);
uni.showToast({
title: "消息发送失败",
icon: "none",
duration: 1500,
});
}
}
};
//
const clearTcpMessages = () => {
tcpMessages.value = [];
uni.showToast({
title: "消息记录已清空",
icon: "success",
duration: 1500,
});
};
// TCP
const getTcpStatus = () => {
const status = tcpConnection.getConnectionStatus();
uni.showModal({
title: "TCP连接状态",
content: `当前状态: ${status ? "已连接" : "未连接"}\n消息数量: ${tcpMessages.value.length}`,
showCancel: false,
});
};
let isMorePacket = 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("init_real_data_start")) || isMorePacket) {
if (typeof message === "string" && message.includes("init_real_data_start")) {
console.log("开始接受分包数据");
receivedMessage = "";
} else {
console.log("接收分包数据过程中");
}
isMorePacket = true;
receivedMessage += message;
// }JSON
if (receivedMessage.includes("init_real_data_complete")) {
console.log("接受分包数据结束");
isMorePacket = false;
console.log("展示数据", receivedMessage);
// JSON
let jsonStartIndex = 0;
let jsonEndIndex = receivedMessage.indexOf("init_real_data_complete");
let jsonStartCount = 0;
let jsonEndCount = 0;
for (let i = 0; i < receivedMessage.length - 1; ++i) {
if (receivedMessage[i] == "{") {
jsonStartCount++;
if (jsonStartCount == 2) {
jsonStartIndex = i;
break;
}
}
}
for (let i = receivedMessage.indexOf("init_real_data_complete"); i >= 0; --i) {
if (receivedMessage[i] == "}" || i == jsonStartIndex) {
jsonEndCount++;
if (jsonEndCount == 1) {
jsonEndIndex = i;
break;
}
}
}
// JSON
if (jsonStartIndex >= jsonEndIndex) {
throw new Error("JSON字符串格式错误");
}
console.log("检测到JSON字符串,开始解析");
parsedMessage = JSON.parse(receivedMessage.substring(jsonStartIndex, jsonEndIndex + 1));
console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
if (parsedMessage.type === "daily_data") {
timeData.value = parsedMessage.data;
stockInformation.value.lastDayStockClosePrice = parsedMessage.pre_close;
console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
drawChart();
}
}
// JSON
console.log("开始处理解析后的数据");
// batch_data_chunkbatch_realtime_data
if ((parsedMessage.type === "batch_data_chunk" || parsedMessage.type === "batch_realtime_data") && parsedMessage.data) {
console.log("开始更新TCP股票数据存储");
// TCP
tcpStockData.value = {
count: parsedMessage.count || 0,
data: parsedMessage.data || {},
stock_count: parsedMessage.stock_count || 0,
timestamp: parsedMessage.timestamp || "",
type: parsedMessage.type || "",
};
//
const stockCodes = Object.keys(parsedMessage.data);
if (stockCodes.length > 0) {
const firstStockCode = stockCodes[0];
//
if (parsedMessage.data[firstStockCode] && Array.isArray(parsedMessage.data[firstStockCode]) && parsedMessage.data[firstStockCode].length > 0) {
const stockData = parsedMessage.data[firstStockCode][0]; //
if (stockData && stockData.current_price !== undefined && stockData.pre_close !== undefined) {
//
const changeValue = stockData.current_price - stockData.pre_close;
const changePercent = ((changeValue / stockData.pre_close) * 100).toFixed(2);
const changeSign = changeValue >= 0 ? "+" : "";
//
currentStockInfo.value = {
stock_name: stockData.stock_name || "未知股票",
current_price: stockData.current_price ? stockData.current_price.toFixed(2) : "0.00",
change: `${changeSign}${changePercent}%`,
change_value: changeValue,
change_percent: parseFloat(changePercent),
};
console.log("股票数据更新成功:", currentStockInfo.value);
}
}
}
} else {
console.log("不是batch_data_chunk或batch_realtime_data类型的消息,跳过处理");
}
} 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消息监听器");
}
};
//
let timer = null;
let index = 0;
@ -1544,8 +1752,8 @@ onLoad((options) => {
// stockInformation
if (stockData) {
stockInformation.value.stockName=stockData.stockName;
stockInformation.value.stockCode=stockData.stockCode;
stockInformation.value.stockName = stockData.stockName;
stockInformation.value.stockCode = stockData.stockCode;
}
} catch (error) {
console.error("解析股票数据失败:", error);
@ -1562,7 +1770,7 @@ onLoad((options) => {
if (stockData) {
stockInformation.value = {
...stockInformation.value,
...stockData
...stockData,
};
}
} catch (error) {
@ -1589,39 +1797,43 @@ onUnmounted(() => {
});
onMounted(async () => {
//
const systemInfo = uni.getSystemInfoSync();
pixelRatio.value = systemInfo.pixelRatio;
// CanvaspixelRatio
// 1rpx = / 750
const rpxToPx = systemInfo.windowWidth / 750;
const offsetHeight = (150 + 200 + 80 + 150 + 30) * rpxToPx; // 350rpxpx
const calculatedHeight = systemInfo.windowHeight - offsetHeight;
canvasWidth.value = systemInfo.windowWidth;
canvasHeight.value = Math.max(calculatedHeight, canvasHeight.value);
// startTcp();
// timeData.value = testTimeData;
timeData.value = testTimeData.slice(0, 100);
klineData.value = testKlineData;
// klineData.value = testKlineData.slice(-touchState.baseVisibleCount);
//
let prevClosePrice = timeData.value[timeData.value.length - 2].price || stockInformation.value.closePrice;
stockInformation.value.lastDayStockClosePrice = prevClosePrice;
//
stockInformation.value.currentPrice = timeData.value[timeData.value.length - 1].price;
//
stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
//
stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
//
stockInformation.value.volume = timeData.value[timeData.value.length - 1].volume;
text[0][1].value = utils.formatPrice(stockInformation.value.currentPrice);
text[1][0].value = utils.formatStockNumber(stockInformation.value.volume);
await nextTick();
setTimeout(() => {
try {
console.log("步骤1: 初始化系统信息");
const systemInfo = uni.getSystemInfoSync();
pixelRatio.value = systemInfo.pixelRatio;
// CanvaspixelRatio
// 1rpx = / 750
const rpxToPx = systemInfo.windowWidth / 750;
const offsetHeight = (150 + 200 + 80 + 150 + 30) * rpxToPx; // 350rpxpx
const calculatedHeight = systemInfo.windowHeight - offsetHeight;
canvasWidth.value = systemInfo.windowWidth;
canvasHeight.value = Math.max(calculatedHeight, canvasHeight.value);
initTcpListeners();
await nextTick();
//
startTcp();
if (timeData.value && timeData.value.length > 0) {
//
stockInformation.value.currentPrice = timeData.value[timeData.value.length - 1].price;
//
stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
//
stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
//
stockInformation.value.volume = timeData.value[timeData.value.length - 1].volume;
text[0][1].value = utils.formatPrice(stockInformation.value.currentPrice);
text[1][0].value = utils.formatStockNumber(stockInformation.value.volume);
} else {
console.warn("没有时间数据,跳过股票信息计算");
}
await nextTick();
initCanvas();
}, 200);
console.log("所有初始化步骤完成");
} catch (error) {
console.error("初始化过程中出现错误:", error);
}
});
</script>

Loading…
Cancel
Save