Procházet zdrojové kódy

新增websocket,同时websocket和proxy改为可拔插

zhusiqing před 3 roky
rodič
revize
e33748e760
8 změnil soubory, kde provedl 105 přidání a 19 odebrání
  1. 22 0
      example/ws.html
  2. 3 1
      package.json
  3. 6 14
      src/app.ts
  4. 11 1
      src/config.ts
  5. 8 3
      src/controllers/index.ts
  6. 1 0
      src/router.ts
  7. 42 0
      src/utils/server.ts
  8. 12 0
      yarn.lock

+ 22 - 0
example/ws.html

@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8">
+  <meta http-equiv="X-UA-Compatible" content="IE=edge">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <title>Document</title>
+</head>
+<body>
+  <button onclick="send()">send</button>
+  <script>
+    const ws = new WebSocket('ws://localhost:9900/ws')
+    ws.onmessage = function (e) {
+      console.log(e.data)
+    }
+    function send() {
+      console.log('click')
+      ws.send('send click')
+    }
+  </script>
+</body>
+</html>

+ 3 - 1
package.json

@@ -37,7 +37,8 @@
     "node-cache": "^5.1.2",
     "nodemon": "^2.0.4",
     "pm2": "^4.4.1",
-    "redis": "^3.0.2"
+    "redis": "^3.0.2",
+    "ws": "^7.5.2"
   },
   "devDependencies": {
     "@types/koa": "^2.11.4",
@@ -47,6 +48,7 @@
     "@types/nedb": "^1.8.11",
     "@types/node": "^14.11.2",
     "@types/redis": "^2.8.27",
+    "@types/ws": "^7.4.6",
     "ts-node": "^9.0.0",
     "tsconfig-paths": "^3.9.0",
     "typescript": "^4.0.3"

+ 6 - 14
src/app.ts

@@ -4,7 +4,6 @@ import Koa, { Context, DefaultState } from 'koa';
 import router from './router';
 // 美化控制台
 // import consola from 'consola/dist/consola';
-import consola from 'consola';
 // 解析post的body体
 import bodyParser from 'koa-bodyparser';
 // 部分安全相关
@@ -25,7 +24,7 @@ import sessionMiddleware from './middlewares/session';
 import localDbMiddleware from './middlewares/localDb';
 
 import { loggerInstance } from '@utils/logger';
-import { getLocalIp } from '@utils/getLocalIp';
+import server from '@utils/server';
 
 const app = new Koa<DefaultState, Context>();
 
@@ -56,12 +55,10 @@ app.use(sessionMiddleware(app))
 // app.use(authMiddleware())
 
 // 请求转发
-app.use(koaProxy('/proxy', {
-  target: 'https://demo.com',
-  changeOrigin: true,
-  logs: true,
-  rewrite: path => path.replace(/^\/proxy(\/|\/\w+)?$/, '/')
-}))
+const { run, ...proxyOptions } = config.proxy
+if (run) {
+  app.use(koaProxy('/proxy', { ...proxyOptions }))
+}
 
 app.on('error', (err, ctx: Context) => {
   ctx.$response(err, 'error', false);
@@ -74,9 +71,4 @@ app.on('error', (err, ctx: Context) => {
 // 注册路由
 app.use(router.routes()).use(router.allowedMethods());
 
-const port = config.port;
-app.listen(port, () => {
-  const ip = getLocalIp()
-  consola.success(`server is started at: http://localhost:${port}`)
-  consola.success(`server is started at: http://${ip}:${port}`)
-});
+server(app)

+ 11 - 1
src/config.ts

@@ -30,5 +30,15 @@ export default {
     doc: 'dbDoc.json',
     tag: 'dbTag.json'
   },
-  secrestKey: 'liaomo'
+  secrestKey: 'liaomo',
+  proxy: {
+    run: false,
+    target: 'https://demo.com',
+    changeOrigin: true,
+    logs: true,
+    rewrite: path => path.replace(/^\/proxy(\/|\/\w+)?$/, '/')
+  },
+  websocket: {
+    run: false
+  }
 };

+ 8 - 3
src/controllers/index.ts

@@ -2,12 +2,16 @@ import { Context } from 'koa';
 import user from './user';
 import document from './document';
 import services from '../services';
-
+import path from 'path';
+import { readFileSync } from 'fs';
 const home = async (ctx: Context) => {
   ctx.body = 'home';
 };
+const ws = async (ctx:Context) => {
+  ctx.body = readFileSync(path.resolve(__dirname, '../../example/ws.html')).toString()
+}
 
-// 读取验证码
+// TODO: 读取验证码,待开发状态
 const code = async (ctx: Context) => {
   interface params {
     phone?: string
@@ -27,5 +31,6 @@ export default {
   home,
   code,
   user,
-  document
+  document,
+  ws
 }

+ 1 - 0
src/router.ts

@@ -21,6 +21,7 @@ apiRouter.delete('/tag/:id', controllers.document.deleteTag);
 // 主路由
 const router = new Router<DefaultState, Context>();
 router.get('/', controllers.home);
+router.get('/ws', controllers.ws);
 // api路由以/api前缀
 router.use('/api', apiRouter.routes(), apiRouter.allowedMethods());
 

+ 42 - 0
src/utils/server.ts

@@ -0,0 +1,42 @@
+import Koa, { DefaultState, Context } from 'koa';
+import WebSocket from 'ws';
+import consola from 'consola';
+import config from '@config';
+import { getLocalIp } from '@utils/getLocalIp';
+
+export default (app: Koa<DefaultState, Context>) => {
+  const port = config.port;
+  const ip = getLocalIp()
+  const server = app.listen(port, () => {
+    consola.success(`server is started at: http://localhost:${port}`)
+    consola.success(`server is started at: http://${ip}:${port}`)
+  });
+  if (config.websocket.run) {
+    const wsServer = new WebSocket.Server({ server }, () => {
+      consola.success(`websocket server is started at: ws://localhost:${port}`)
+      consola.success(`websocket server is started at: ws://${ip}:${port}`)
+    })
+    wsServer.on('error', (err) => {
+      consola.error('websocket error >>>', err)
+    }).on('close', () => {
+      consola.info('websocket is closed')
+    })
+    wsServer.on('connection', ws => {
+      console.log('ws is connectioned');
+      ws.on('message', msg => {
+        console.log(msg);
+        const obj = {
+          msg,
+          code: 200
+        }
+        ws.send(JSON.stringify(obj), err => {
+          if (err) {
+            consola.error('websocket send >>>', err)
+          }
+        })
+      })
+
+    })
+  }
+  return server
+}

+ 12 - 0
yarn.lock

@@ -273,6 +273,13 @@
     "@types/express-serve-static-core" "*"
     "@types/mime" "*"
 
+"@types/ws@^7.4.6":
+  version "7.4.6"
+  resolved "https://registry.yarnpkg.com/@types/ws/-/ws-7.4.6.tgz#c4320845e43d45a7129bb32905e28781c71c1fff"
+  integrity sha512-ijZ1vzRawI7QoWnTNL8KpHixd2b2XVb9I9HAqI3triPsh1EC0xH0Eg6w2O3TKbDCgiNNlJqfrof6j4T2I+l9vw==
+  dependencies:
+    "@types/node" "*"
+
 abbrev@1:
   version "1.1.1"
   resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"
@@ -2717,6 +2724,11 @@ ws@^7.0.0:
   resolved "https://registry.yarnpkg.com/ws/-/ws-7.3.1.tgz#d0547bf67f7ce4f12a72dfe31262c68d7dc551c8"
   integrity sha512-D3RuNkynyHmEJIpD2qrgVkc9DQ23OrN/moAwZX4L8DfvszsJxpjQuUq3LMx6HoYji9fbIOBY18XWBsAux1ZZUA==
 
+ws@^7.5.2:
+  version "7.5.2"
+  resolved "https://registry.yarnpkg.com/ws/-/ws-7.5.2.tgz#09cc8fea3bec1bc5ed44ef51b42f945be36900f6"
+  integrity sha512-lkF7AWRicoB9mAgjeKbGqVUekLnSNO4VjKVnuPHpQeOxZOErX6BPXwJk70nFslRCEEA8EVW7ZjKwXaP9N+1sKQ==
+
 ws@~7.2.0:
   version "7.2.5"
   resolved "https://registry.yarnpkg.com/ws/-/ws-7.2.5.tgz#abb1370d4626a5a9cd79d8de404aa18b3465d10d"