You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.7 KiB
83 lines
2.7 KiB
3 weeks ago
|
function getWsUrl() {
|
||
|
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
|
||
|
const host = window.location.host; // 包含主机和端口(如 localhost:5000)
|
||
|
const path = "/api/ws"; // 你的 WebSocket 路由
|
||
|
return `${protocol}://${host}${path}`;
|
||
|
}
|
||
|
|
||
|
function initWebSocket() {
|
||
|
// 替换成你实际的 WebSocket 地址,例如 ws://localhost:5000/ws
|
||
|
wsUrl = getWsUrl();
|
||
|
const ws = new WebSocket(wsUrl);
|
||
|
// 设置接收二进制数据为 ArrayBuffer
|
||
|
ws.binaryType = "arraybuffer";
|
||
|
|
||
|
ws.onopen = function() {
|
||
|
console.log("WebSocket 已连接");
|
||
|
// 发送登录数据包,假设格式为 JSON(后端可以根据需要解析此包) --暂时默认0只有一个
|
||
|
ws.send(JSON.stringify({ user_id: 0 }));
|
||
|
};
|
||
|
|
||
|
ws.onmessage = function(event) {
|
||
|
// 解析收到的二进制数据
|
||
|
const buffer = event.data;
|
||
|
const dataView = new DataView(buffer);
|
||
|
// 读取前四个字节,验证魔数 "TFTF"
|
||
|
let magic = "";
|
||
|
for (let i = 0; i < 4; i++) {
|
||
|
magic += String.fromCharCode(dataView.getUint8(i));
|
||
|
}
|
||
|
if (magic !== "TFTF") {
|
||
|
console.error("收到非法格式数据:", magic);
|
||
|
return;
|
||
|
}
|
||
|
// 读取数据头:接下来的 8 字节分别为 idata_type 和 idata_len(均为 32 位无符号整数,假设大端)
|
||
|
const idata_type = dataView.getUint32(4, false);
|
||
|
const idata_len = dataView.getUint32(8, false);
|
||
|
|
||
|
// 数据体从偏移量 12 开始,长度为 idata_len
|
||
|
const bodyBytes = new Uint8Array(buffer, 12, idata_len);
|
||
|
const decoder = new TextDecoder("utf-8");
|
||
|
const bodyText = decoder.decode(bodyBytes);
|
||
|
// 假设数据体为 JSON 字符串
|
||
|
let bodyData;
|
||
|
try {
|
||
|
bodyData = JSON.parse(bodyText);
|
||
|
} catch (error) {
|
||
|
console.error("解析数据体出错:", error);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// 针对 idata_type 为 1 的处理:更新节点
|
||
|
if(idata_type === 0){
|
||
|
console.log(bodyData);
|
||
|
}
|
||
|
else if (idata_type === 1) {//type-1为更新节点的node_workstatus
|
||
|
// bodyData 应该包含 node_path 和 node_workstatus 两个字段
|
||
|
updateTreeNode(bodyData.node_path, bodyData.node_workstatus);//node_tree.js
|
||
|
}
|
||
|
else if(idata_type === 2){
|
||
|
if(cur_task_id === 0){return;}
|
||
|
// 清空选中状态
|
||
|
selectedNodeData = null;
|
||
|
//刷新界面内容
|
||
|
update_select_node_data_show("-","-","-","-","-",false)
|
||
|
// 重新加载节点树数据
|
||
|
loadNodeTree(cur_task_id);
|
||
|
}
|
||
|
else {
|
||
|
console.error("未知的数据类型");
|
||
|
}
|
||
|
};
|
||
|
|
||
|
ws.onerror = function(error) {
|
||
|
console.error("WebSocket 错误:", error);
|
||
|
};
|
||
|
|
||
|
ws.onclose = function() {
|
||
|
console.log("WebSocket 连接关闭");
|
||
|
};
|
||
|
|
||
|
return ws;
|
||
|
}
|