gemercheung 3 jaren geleden
bovenliggende
commit
b33790d8a7
6 gewijzigde bestanden met toevoegingen van 59 en 113 verwijderingen
  1. 0 6
      config.dev.yaml
  2. 1 12
      config.production2.yaml
  3. 7 59
      src/app.controller.ts
  4. 27 7
      src/logConfig.ts
  5. 1 0
      src/main.ts
  6. 23 29
      src/meta.gateway.ts

+ 0 - 6
config.dev.yaml

@@ -51,9 +51,3 @@ server:
   private_ip: 172.18.197.114
   public_ip: 120.24.252.95
 
-  
-# PRIVATE_IP=172.18.197.114
-# PUBLIC_IP=120.24.252.95
-# STUNS_SEVER="stun:172.18.156.41:3478,stun:120.24.252.95:3478"
-# GRPC_URL="192.168.0.48:3000"
-# REDIS_URL="redis://:192.168.0.47:6379/9"

+ 1 - 12
config.production2.yaml

@@ -19,19 +19,12 @@ grpc:
   url: '221.4.210.172:23000'
 # grpc:
 #   url: '192.168.0.47:3000'
-
 redis:
   port: 6379
   host: '127.0.0.1' #远程调试需要设置bindip 为0.0.0.0 并且设置密码
   password: 'Happy@Pass#@!7' # 非远程不需要密码
   decode_responses: true
   db: 9
-# queueRedis:
-#   port: 6379
-#   host: '127.0.0.1' #远程调试需要设置bindip 为0.0.0.0 并且设置密码
-#   password: 'sxz123321SxZ@' # 非远程不需要密码
-#   decode_responses: true
-#   db: 14
 # server: ['stun:47.107.125.202:3478','stun:120.24.252.95:3478']
 #  server: ['stun:4dage:4dage168@47.107.125.202:3478','stun:120.24.252.95:3478']
 # ['turn:4dage:4dage168@turn.4dage.com:4478', 'stun:stun.callwithus.com:3478']
@@ -44,8 +37,4 @@ stun:
 server:
   private_ip: 172.16.0.3
   public_ip: 106.52.6.134
-# PRIVATE_IP=172.18.197.114
-# PUBLIC_IP=120.24.252.95
-# STUNS_SEVER="stun:172.18.156.41:3478,stun:120.24.252.95:3478"
-# GRPC_URL="192.168.0.48:3000"
-# REDIS_URL="redis://:192.168.0.47:6379/9"
+

+ 7 - 59
src/app.controller.ts

@@ -12,7 +12,7 @@ export class AppController implements OnModuleInit {
   constructor(
     private readonly appService: AppService,
     private readonly sceneService: SceneService,
-  ) {}
+  ) { }
 
   onModuleInit() {
     // console.log('this.client', this.client);
@@ -20,65 +20,13 @@ export class AppController implements OnModuleInit {
     //   this.client.getService<SceneGrpcService>('SceneGrpcService');
     // console.log('this.sceneGrpcService', this.sceneGrpcService);
   }
+  @Get('/api/online')
+  getOnline(): string {
+    return 'xxxxxxx';
+  }
+
   @Get()
   getHello(): string {
-    // console.log('UtilsModule', UtilsModule);
-    // const params: RouteRequest = {
-    //   sLocation: {
-    //     x: '6.0',
-    //     y: '0.0',
-    //     z: '-4.0',
-    //   },
-    //   eLocation: {
-    //     x: '4.0',
-    //     y: '0.0',
-    //     z: '-3.0',
-    //   },
-    //   sceneCode: 'Hello',
-    // };
-    // // // console.log('params', params);
-    // const test = this.sceneGrpcService.getRoute(params);
-    // test.subscribe((val) => {
-    //   console.log('val', val);
-    // });
-
-    try {
-      // const demo_test = {
-      //   user_id: '92dd7e2f-cca9-495d-8f16-458e628ea827',
-      //   nick_name: 'Hello',
-      //   skin_id: 'ce098a8f-a7fc-4721-9c37-31bdbc580c59',
-      //   avatar_id: 'c961561e-78e5-4478-b158-944e3b9c9287',
-      //   room_id: 'c38187b6-d4af-44bb-8028-7ad1e5461cd8',
-      //   app_id: '2282e1b5-6129-4e0d-a30b-2339a1c761cd',
-      //   player: {
-      //     position: {
-      //       x: '0.0',
-      //       y: '0.0',
-      //       z: '0.0',
-      //     },
-      //     angle: {
-      //       pitch: 10,
-      //       yaw: 10,
-      //       roll: 10,
-      //     },
-      //   },
-      // };
-      // const initReply = this.sceneGrpcService.init(demo_test);
-      // initReply.subscribe((val) => {
-      //   console.log('val', val);
-      // });
-      // const params = {
-      //   action_type: 1009,
-      //   echo_msg: {
-      //     echoMsg: 'Hello',
-      //   },
-      //   trace_id: '2b6e3444-63eb-40a7-8049-1d6616f16664',
-      //   user_id: '31a6322c-78f1-4744-99df-bc042f50bebc',
-      // };
-      // console.log('initReply');
-    } catch (error) {
-      console.log('test', error);
-    }
-    return this.appService.getHello();
+    return 'xx';
   }
 }

+ 27 - 7
src/logConfig.ts

@@ -13,19 +13,34 @@ if (process.env.NODE_ENV === 'production') {
   console.log('正式服log', logDir);
 }
 console.log('logDir', logDir);
+
+const levels = {
+  levels: {
+    error: 0,
+    warn: 1,
+    info: 2,
+    http: 3,
+    verbose: 4,
+    debug: 5,
+    silly: 6,
+  },
+};
 export const LoggerConfig = {
+  levels: levels.levels,
   format: winston.format.combine(
+    winston.format.ms(),
     winston.format.timestamp({
       format: 'YYYY-MM-DD HH:mm:ss SSS',
     }),
-    winston.format.ms(),
     winston.format.json(),
-    // winston.format.printf(
-    //   (info) => `${info.timestamp} ${info.level}: ${info.message}`,
-    // ),
-    nestWinstonModuleUtilities.format.nestLike('Meta-server', {
-      prettyPrint: false,
-    }),
+    winston.format.printf(
+      (info) =>
+        `${info.timestamp} [${info.level}] ${info.context || ''}: ${info.message
+        }`,
+    ),
+    // nestWinstonModuleUtilities.format.nestLike('Meta-server', {
+    //   prettyPrint: false,
+    // }),
   ),
   exitOnError: false,
   transports: [
@@ -45,6 +60,11 @@ export const LoggerConfig = {
     //   filename: 'error.log',
     //   level: 'error',
     // }),
+    new winston.transports.File({
+      dirname: logDir,
+      filename: 'bootsrap.log',
+      level: 'http',
+    }),
 
     new winston.transports.File({
       dirname: logDir,

+ 1 - 0
src/main.ts

@@ -7,6 +7,7 @@ import { ConfigService } from '@nestjs/config';
 import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
 import { WinstonModule } from 'nest-winston';
 import { LoggerConfig } from './logConfig';
+
 async function bootstrap() {
   const app = await NestFactory.create(AppModule, {
     logger: WinstonModule.createLogger(LoggerConfig),

+ 23 - 29
src/meta.gateway.ts

@@ -18,13 +18,14 @@ import {
 } from 'node-datachannel';
 
 import { Buffer } from 'buffer';
-import { Logger } from '@nestjs/common';
+import { Inject } from '@nestjs/common';
 import * as path from 'path';
 import { createReadStream } from 'fs';
 import { SceneService } from './scene/scene.service';
 import { ConfigService } from '@nestjs/config';
 import { stringify } from 'querystring';
-
+import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
+import { Logger } from 'winston';
 // 'Verbose' | 'Debug' | 'Info' | 'Warning' | 'Error' | 'Fatal';
 initLogger('Debug');
 
@@ -35,13 +36,13 @@ initLogger('Debug');
   path: '/ws',
 })
 export class MetaGateway
-  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
-{
+  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
   constructor(
     private readonly sceneService: SceneService,
     private readonly configService: ConfigService,
-  ) {}
-  private logger: Logger = new Logger('MetaGateway');
+    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
+  ) { }
+  // private logger: Logger = new Logger('MetaGateway');
   private peer: PeerConnection = null;
   private timer: NodeJS.Timeout;
   private _webrtcInterval: NodeJS.Timeout;
@@ -52,17 +53,13 @@ export class MetaGateway
   private startstreamingSub: any;
   @WebSocketServer() server: Server;
 
-  // @SubscribeMessage('message')
-  // handleMessage(client: any, payload: any) {
-  //   this.logger.log(`payload: ${JSON.stringify(payload)}`);
-  // }
   afterInit(server: Server) {
-    this.logger.log('Init MetaGateway');
+    this.logger.info('Init MetaGateway');
   }
 
   @SubscribeMessage('init')
   handleInit(client: any, payload: any) {
-    this.logger.log(`socket::init: ${JSON.stringify(payload)}`);
+    this.logger.info(`socket::init: ${JSON.stringify(payload)}`);
   }
 
   @SubscribeMessage('heartbeat')
@@ -90,7 +87,8 @@ export class MetaGateway
   handleInitWebRtc(client: any, payload: any): void {
     // TODO 可能会中断连接
     // cleanup();
-    this.logger.log('action::handleInitWebRtc', JSON.stringify(payload));
+    this.logger.info('action::handleInitWebRtc', JSON.stringify(payload));
+    this.logger.log('http', `socket::开始`);
     const stun_server = this.configService.get('stun.server');
     const portRangeBegin = this.configService.get('stun.portRangeBegin');
     const portRangeEnd = this.configService.get('stun.portRangeEnd');
@@ -112,14 +110,14 @@ export class MetaGateway
         id: 'offer',
         data: Buffer.from(JSON.stringify(offer)).toString('base64'),
       };
-      this.logger.log('peer::onLocalDescription', JSON.stringify(offerFormat));
+      this.logger.info('peer::onLocalDescription', JSON.stringify(offerFormat));
       client.send(JSON.stringify(offerFormat));
     });
 
     const replaceToPublic = (candidate) => {
       const PRIVATE_IP = this.configService.get('server.private_ip');
       const PUBLIC_IP = this.configService.get('server.public_ip');
-      this.logger.log(
+      this.logger.info(
         'peer::replaceToPublic',
         `private_ip:${PRIVATE_IP} to public_ip:${PUBLIC_IP}`,
       );
@@ -128,7 +126,9 @@ export class MetaGateway
 
     this.peer.onLocalCandidate((candidate, mid) => {
       if (/172\./.test(candidate)) {
-        this.logger.log('server private Ip process', JSON.stringify(candidate));
+        this.logger.info(
+          'server private Ip process' + JSON.stringify(candidate),
+        );
         const PRIVATE_IP = this.configService.get('server.private_ip');
         if (candidate.includes(PRIVATE_IP)) {
           candidate = replaceToPublic(candidate);
@@ -142,10 +142,6 @@ export class MetaGateway
           this.logger.warn('不是192.168.0./192.168.10测试网段' + candidate);
           return;
         }
-        // if (candidate.includes(process.env.PRIVATE_IP)) {
-        //   console.error('PRIVATE_IP', process.env.PRIVATE_IP);
-        //   candidate = replaceToPublic(candidate);
-        // }
       }
       this.logger.warn('onLocalCandidate last Candidate:' + candidate);
 
@@ -192,15 +188,14 @@ export class MetaGateway
     });
 
     this.gameChanel.onOpen(() => {
-      this.logger.log('channel is open');
       if (this.gameChanel.isOpen()) {
+        this.logger.info('channel is open');
         const peers = this.peer.getSelectedCandidatePair();
-        this.logger.log('配对成功', JSON.stringify(peers));
-        console.log('gameChanel', this.gameChanel.isOpen());
+        this.logger.info('配对成功::' + JSON.stringify(peers));
         this.sendWertcHeartPack(this.gameChanel);
         this.sceneService.handleDataChanelOpen(this.gameChanel, this.peer);
       } else {
-        console.log('gameChanel has problem');
+        this.logger.error('gameChanel has problem');
       }
 
       // Number.prototype.padLeft = function (n, str) {
@@ -243,8 +238,7 @@ export class MetaGateway
   handlerIceCandidate(client: any, payload: any) {
     const iceCandidate = Buffer.from(payload, 'base64').toString('utf-8');
     const candidate = JSON.parse(iceCandidate);
-    // console.warn('收到ice_candidate',);
-    this.logger.log('server get ice_candidate', JSON.stringify(candidate));
+    this.logger.info('server get ice_candidate' + JSON.stringify(candidate));
     this.peer.addRemoteCandidate(candidate.candidate, candidate.sdpMid);
   }
 
@@ -292,7 +286,7 @@ export class MetaGateway
           }
         },
       );
-    } catch (error) {}
+    } catch (error) { }
   }
 
   handleConnection(client: WebSocket, ...args: any[]) {
@@ -310,7 +304,7 @@ export class MetaGateway
     const reconnect = params.get('reconnect');
     this.sceneService.setConfig(this.user_id, this.roomId);
 
-    this.logger.log(`Client connected:`);
+    this.logger.info(`Client connected:`);
 
     const connected = {
       channel_id: '',
@@ -329,7 +323,7 @@ export class MetaGateway
     client.send(tt);
   }
   handleDisconnect(client: WebSocket) {
-    this.logger.log(`Client disconnected: ${client.id}`);
+    this.logger.info(`Client disconnected: ${client.id}`);
     this.peer && this.peer.close();
     if (this.startstreamingSub) {
       this.startstreamingSub.unsubscribe();