CzRger 1 jaar geleden
bovenliggende
commit
0e4ce4b458

+ 10 - 1
config.json

@@ -1,7 +1,7 @@
 {
   "port": 18061,
   "ship-test": {
-    "version": "182",
+    "version": "192",
     "182": {
       "db": {
         "host": "8.140.240.182",
@@ -19,6 +19,15 @@
         "password": "Taiji@2023#seat",
         "database": "seat_tools"
       }
+    },
+    "192": {
+      "db": {
+        "host": "yvu7o29.nat.ipyingshe.com",
+        "port": "28900",
+        "user": "root",
+        "password": "root",
+        "database": "seat_tools"
+      }
     }
   }
 }

+ 2 - 1
package.json

@@ -20,6 +20,7 @@
     "mycp": "^1.0.3",
     "mysql": "^2.18.1",
     "nodemon": "^3.0.3",
-    "pkg": "^5.8.1"
+    "pkg": "^5.8.1",
+    "ws": "^8.16.0"
   }
 }

+ 5 - 0
src/app.js

@@ -29,3 +29,8 @@ app.listen(port, () => {
     console.log('express server running at ' + port);
 })
 
+// 引入ws模块
+const WebSocket = require('ws');
+// 创建WebSocket服务器
+const wsShipPlayback = require('./ship-playback/routers/ws-ship-playback');
+wsShipPlayback(new WebSocket.Server({ port: 18062 }))

+ 19 - 0
src/ship-playback/config/api.js

@@ -0,0 +1,19 @@
+const resultCode = {
+    200: '请求成功',
+    500: '请求失败'
+}
+module.exports = class ApiResult {
+    constructor(code, data, msg) {
+        this.code = code
+        this.data = data
+        this.msg = msg
+    }
+    success(data, msg) {
+        const c = 200
+        return new ApiResult(c, data, msg || resultCode[c])
+    }
+    error(data, msg) {
+        const c = 500
+        return new ApiResult(c, data, msg || resultCode[c])
+    }
+}

+ 48 - 0
src/ship-playback/config/db.js

@@ -0,0 +1,48 @@
+const mysql = require('mysql')
+const fs = require("fs");
+const configFile = fs.readFileSync('./config.json');
+const globalConfig = JSON.parse(configFile)
+const shipTestConfig = globalConfig['ship-test'][globalConfig['ship-test']['version']]
+const db_config = shipTestConfig.db
+// 进行数据库交互
+const sqlHandle = (sql, values) => {
+    let connect = mysql.createConnection(db_config)
+    // 开始链接数据库
+    connect.connect(function (err) {
+        if (err) {
+            console.log(`mysql连接失败: ${err}!`)
+        } else {
+            console.log('mysql连接成功!')
+        }
+    })
+    // 返回一个Promise承诺对象
+    return new Promise((resolve, reject) => {
+        connect.query(sql, values, (err, result) => {
+            if (err) {
+                reject(err)
+            } else {
+                // 此处需要将返回数据转为JSON再转回来,否则原数据不为任何数据类型
+                let res = JSON.parse(JSON.stringify(result))
+                console.log('执行:', sql)
+                console.log('参数:', values)
+                console.log('结果:', res)
+                closeMysql(connect)
+                resolve(res)
+            }
+        });
+    })
+}
+// 查询成功后关闭mysql
+const closeMysql = (connect) => {
+    connect.end((err) => {
+        if (err) {
+            console.log(`mysql关闭失败:${err}!`)
+        } else {
+            console.log('mysql关闭成功!')
+        }
+    })
+}
+// 导出方法
+module.exports = {
+    sqlHandle
+}

+ 10 - 0
src/ship-playback/config/page.js

@@ -0,0 +1,10 @@
+const {sqlHandle} = require("./db")
+
+const PageResult = async (sql, pageNum, pageSize, Entity) => {
+    const result = await sqlHandle(sql)
+    return {
+        data: result.slice((pageNum - 1) * pageSize, pageNum * pageSize).map(v => Entity ? new Entity(v) : v),
+        total: result.length
+    }
+}
+module.exports = PageResult

+ 3 - 0
src/ship-playback/routers/index.js

@@ -0,0 +1,3 @@
+const express = require("express")
+const shipPlaybackRouter = express.Router()
+module.exports = shipPlaybackRouter

+ 41 - 0
src/ship-playback/routers/ws-ship-playback.js

@@ -0,0 +1,41 @@
+const {randomNum} = require("../../util");
+const wsShipPlayback = (WebSocket) => {
+// 服务器端监听连接事件
+  WebSocket.on('connection', (ws) => {
+    console.log('18062:WebSocket连接成功');
+    // 监听客户端发送的消息
+    ws.on('message', (message) => {
+      const params = JSON.parse(message)
+      const sendResult = () => {
+        const result = initPointsFeature(5000)
+        ws.send(JSON.stringify(result))
+      }
+      sendResult()
+      setInterval(() => {
+        sendResult()
+      }, 1000)
+    });
+    // 监听连接断开事件
+    ws.on('close', () => {
+      console.log('18062:WebSocket关闭成功');
+    });
+  });
+}
+
+const initPointsFeature = (total = 1) => {
+  const arr = []
+  for (let i = 0; i < total; i++) {
+    arr.push({
+      type: 'Feature',
+      geometry: {
+        type: 'Point',
+        coordinates: [randomNum(107, 112, 6), randomNum(17, 20, 6)]
+      },
+      properties: {
+        title: i
+      }
+    })
+  }
+  return arr
+}
+module.exports = wsShipPlayback

+ 39 - 0
src/util/index.js

@@ -59,4 +59,43 @@ module.exports.Hms = (date, format = false) => {
   const m = `${_date.getMinutes() < 10 ? `0${_date.getMinutes()}` : _date.getMinutes()}`;
   const s = _date.getSeconds() < 10 ? `0${_date.getSeconds()}` : _date.getSeconds();
   return format ? `${H}时${m}分${s}秒` : `${H}:${m}:${s}`;
+}
+
+module.exports.randomNum = (min = 0, max = 0, decimal=0) => {
+  // 获取数值的小数部分
+  const getDecimalNum = (data) => {
+    return Number(data.toString().split('.')[1]);
+  }
+  let min_z = Math.trunc(min); // 最小值的整数部分
+  let max_z = Math.trunc(max); // 最大值的整数部分
+  // 判断是否存在小数部分,不存在的话为0
+  let min_x = isNaN(getDecimalNum(min)) ? 0 : getDecimalNum(min);  // 最小值的小数部分
+  let max_x = isNaN(getDecimalNum(max)) ? 0 : getDecimalNum(max);  // 最大值的小数部分
+
+  // 区分有小数和没小数的情况
+  if (min_x > 0 || max_x > 0 || decimal > 0) {
+    // 整数部分随机数
+    let z = parseInt(String(Math.random() * (max_z - min_z + 1) + min_z), 10);
+    // 小数部分随机数
+    let x = 0;
+    // 小数部分随机数最大位数
+    let max_decimal = min_x.toString().length > max_x.toString().length ? min_x.toString().length : max_x.toString().length;
+    max_decimal = decimal > max_decimal ? decimal : max_decimal;
+    // 判断随机出的整数部分,是否等于最小值或者最大值
+    if(z == min_z || z == max_z){
+      if(z == min_z){
+        // 整数部分随机数等于最小值,那么应该从最小值的小数部分开始,到小数位数的最大值随机就可以
+        x = parseInt(String(Math.random() * (Math.pow(10, max_decimal) - min_x) + min_x), 10);
+      }else{
+        // 整数部分随机数等于最大值,那么应该从0开始,到最大值小数部分
+        x = parseInt(String(Math.random() * (max_x + 1)), 10);
+      }
+    }else{
+      // 整数部分在最大最小值区间的,就从0到小数位数的最大值随机就可以
+      x = parseInt(String(Math.random() * (Math.pow(10, max_decimal))), 10);
+    }
+    return Number(`${z}.${x}`);
+  } else {
+    return parseInt(String(Math.random() * (max_z - min_z + 1) + min_z), 10);
+  }
 }