index.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import Koa from 'koa';
  2. import path from 'path';
  3. import Router from 'koa-router';
  4. import body from 'koa-body';
  5. import cors from 'koa2-cors';
  6. import koaStatic from 'koa-static';
  7. import websockify from 'koa-websocket';
  8. import route from 'koa-route';
  9. import AppRoutes from './routes';
  10. const PORT = 3300;
  11. const app = websockify(new Koa());
  12. app.ws.use(function (ctx, next) {
  13. ctx.websocket.send('connection succeeded!');
  14. return next(ctx);
  15. });
  16. app.ws.use(
  17. route.all('/test', function (ctx) {
  18. // ctx.websocket.send('Hello World');
  19. ctx.websocket.on('message', function (message) {
  20. // do something with the message from client
  21. if (message !== 'ping') {
  22. const data = JSON.stringify({
  23. id: Math.ceil(Math.random() * 1000),
  24. time: new Date().getTime(),
  25. res: `${message}`,
  26. });
  27. ctx.websocket.send(data);
  28. }
  29. console.log(message);
  30. });
  31. }),
  32. );
  33. const router = new Router();
  34. // router
  35. AppRoutes.forEach((route) => router[route.method](route.path, route.action));
  36. app.use(cors());
  37. app.use(
  38. body({
  39. encoding: 'gzip',
  40. multipart: true,
  41. formidable: {
  42. // uploadDir: path.join(__dirname, '/upload/'), // 设置文件上传目录
  43. keepExtensions: true,
  44. maxFieldsSize: 20 * 1024 * 1024,
  45. },
  46. }),
  47. );
  48. app.use(router.routes());
  49. app.use(router.allowedMethods());
  50. app.use(koaStatic(path.join(__dirname)));
  51. app.listen(PORT, () => {
  52. console.log(`Application started successfully: http://localhost:${PORT}`);
  53. });