meta.gateway.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import {
  2. SubscribeMessage,
  3. WebSocketGateway,
  4. OnGatewayInit,
  5. WebSocketServer,
  6. OnGatewayConnection,
  7. OnGatewayDisconnect,
  8. } from '@nestjs/websockets';
  9. import { Server } from 'ws';
  10. import * as WebSocket from 'ws';
  11. import {
  12. PeerConnection,
  13. initLogger,
  14. DataChannel,
  15. cleanup,
  16. } from 'node-datachannel';
  17. import { Buffer } from 'buffer';
  18. import { Logger } from '@nestjs/common';
  19. import * as path from 'path';
  20. import { createReadStream } from 'fs';
  21. import { SceneService } from './scene/scene.service';
  22. import { ConfigService } from '@nestjs/config';
  23. import { stringify } from 'querystring';
  24. // 'Verbose' | 'Debug' | 'Info' | 'Warning' | 'Error' | 'Fatal';
  25. initLogger('Debug');
  26. @WebSocketGateway({
  27. transports: ['websocket'],
  28. cors: '*',
  29. // namespace: "ws",
  30. path: '/ws',
  31. })
  32. export class MetaGateway
  33. implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  34. constructor(
  35. private readonly sceneService: SceneService,
  36. private readonly configService: ConfigService,
  37. ) { }
  38. private logger: Logger = new Logger('MetaGateway');
  39. private peer: PeerConnection = null;
  40. private timer: NodeJS.Timeout;
  41. private _webrtcInterval: NodeJS.Timeout;
  42. private heartBeatFlag: number;
  43. private gameChanel: DataChannel;
  44. private user_id: string;
  45. private roomId: string;
  46. private startstreamingSub: any;
  47. @WebSocketServer() server: Server;
  48. // @SubscribeMessage('message')
  49. // handleMessage(client: any, payload: any) {
  50. // this.logger.log(`payload: ${JSON.stringify(payload)}`);
  51. // }
  52. afterInit(server: Server) {
  53. this.logger.log('Init MetaGateway');
  54. }
  55. @SubscribeMessage('init')
  56. handleInit(client: any, payload: any) {
  57. this.logger.log(`socket::init: ${JSON.stringify(payload)}`);
  58. }
  59. @SubscribeMessage('heartbeat')
  60. handleHeartBeat(client: any, payload: any) {
  61. // this.logger.log(`heartbeat: ${JSON.stringify(payload)}`);
  62. // console.log('hb', payload);
  63. this.heartBeatFlag = payload;
  64. const pong = {
  65. channel_id: '',
  66. client_os: '',
  67. data: payload,
  68. fe_version: '',
  69. id: 'heartbeat',
  70. packet_id: '',
  71. room_id: '',
  72. session_id: '',
  73. trace_id: '',
  74. user_id: '',
  75. };
  76. return pong;
  77. }
  78. @SubscribeMessage('init_webrtc')
  79. handleInitWebRtc(client: any, payload: any): void {
  80. this.logger.log('action::handleInitWebRtc', JSON.stringify(payload));
  81. const stun_server = this.configService.get('stun.server');
  82. const portRangeBegin = this.configService.get('stun.portRangeBegin');
  83. const portRangeEnd = this.configService.get('stun.portRangeEnd');
  84. this.peer = new PeerConnection('roomTest', {
  85. portRangeBegin: portRangeBegin,
  86. portRangeEnd: portRangeEnd,
  87. iceServers: stun_server,
  88. });
  89. this.peer.onLocalDescription((sdp, type) => {
  90. // console.warn('peer SDP:', sdp, ' Type:', type);
  91. const offer = { sdp, type };
  92. const offerFormat = {
  93. id: 'offer',
  94. data: Buffer.from(JSON.stringify(offer)).toString('base64'),
  95. };
  96. this.logger.log('peer::onLocalDescription', JSON.stringify(offerFormat));
  97. client.send(JSON.stringify(offerFormat));
  98. });
  99. const replaceToPublic = (candidate) => {
  100. const PRIVATE_IP = this.configService.get('server.private_ip');
  101. const PUBLIC_IP = this.configService.get('server.public_ip');
  102. this.logger.log(
  103. 'peer::replaceToPublic',
  104. `private_ip:${PRIVATE_IP} to public_ip:${PUBLIC_IP}`,
  105. );
  106. return candidate.replace(PRIVATE_IP, PUBLIC_IP);
  107. };
  108. this.peer.onLocalCandidate((candidate, mid) => {
  109. if (/172\./.test(candidate)) {
  110. this.logger.log('server private Ip process', JSON.stringify(candidate));
  111. const PRIVATE_IP = this.configService.get('server.private_ip');
  112. if (candidate.includes(PRIVATE_IP)) {
  113. candidate = replaceToPublic(candidate);
  114. } else {
  115. return;
  116. }
  117. }
  118. if (/192.168\./.test(candidate)) {
  119. if (!/192.168.0\./.test(candidate) || !/192.168.10\./.test(candidate)) {
  120. console.warn('不是192.168.0./192.168.10测试网段', candidate);
  121. return;
  122. }
  123. // if (candidate.includes(process.env.PRIVATE_IP)) {
  124. // console.error('PRIVATE_IP', process.env.PRIVATE_IP);
  125. // candidate = replaceToPublic(candidate);
  126. // }
  127. }
  128. console.warn('onLocalCandidate last Candidate:', candidate);
  129. const iceRes = {
  130. candidate,
  131. sdpMid: mid,
  132. sdpMLineIndex: 0,
  133. };
  134. const res = {
  135. channel_id: '',
  136. client_os: '',
  137. data: Buffer.from(JSON.stringify(iceRes)).toString('base64'),
  138. fe_version: '',
  139. id: 'ice_candidate',
  140. packet_id: '',
  141. room_id: '',
  142. session_id: '',
  143. trace_id: '',
  144. user_id: '',
  145. };
  146. client.send(JSON.stringify(res));
  147. });
  148. this.peer.onStateChange((state) => {
  149. console.log('peer-State:', state);
  150. });
  151. this.peer.onGatheringStateChange((state) => {
  152. console.log('GatheringState:', state);
  153. });
  154. this.peer.onTrack((track) => {
  155. console.log('track', track);
  156. });
  157. this.gameChanel = this.peer.createDataChannel('game-input');
  158. this.peer.onDataChannel((dc) => {
  159. console.log('onDataChannel', dc);
  160. });
  161. this.gameChanel.onOpen(() => {
  162. console.log('channel is open');
  163. this.sceneService.handleDataChanelOpen(this.gameChanel);
  164. const peers = this.peer.getSelectedCandidatePair();
  165. this.logger.log('配对成功', JSON.stringify(peers));
  166. if (this.gameChanel.isOpen()) {
  167. console.log('gameChanel', this.gameChanel.isOpen());
  168. this.sendWertcHeartPack(this.gameChanel);
  169. }
  170. // Number.prototype.padLeft = function (n, str) {
  171. // return Array(n - String(this).length + 1).join(str || '0') + this;
  172. // };
  173. });
  174. this.gameChanel.onClosed(() => {
  175. console.log('gameChanel close');
  176. this.sceneService.handleDataChanelClose();
  177. this.stopSendWertcHeartPack();
  178. cleanup();
  179. this.startstreamingSub & this.startstreamingSub.unsubscribe();
  180. });
  181. this.gameChanel.onMessage((event) => {
  182. this.sceneService.handleMessage(event);
  183. });
  184. this.gameChanel.onError(() => {
  185. console.log('gameChanel onError');
  186. this.stopSendWertcHeartPack();
  187. });
  188. }
  189. sendWertcHeartPack(channel: DataChannel) {
  190. const heartPack = new DataView(new ArrayBuffer(4));
  191. heartPack.setUint32(0, 2009889916);
  192. this._webrtcInterval = setInterval(() => {
  193. if (channel && channel.isOpen()) {
  194. channel.sendMessageBinary(Buffer.from(heartPack.buffer));
  195. }
  196. }, 200);
  197. }
  198. stopSendWertcHeartPack(): void {
  199. clearInterval(this._webrtcInterval);
  200. }
  201. @SubscribeMessage('ice_candidate')
  202. handlerIceCandidate(client: any, payload: any) {
  203. const iceCandidate = Buffer.from(payload, 'base64').toString('utf-8');
  204. const candidate = JSON.parse(iceCandidate);
  205. // console.warn('收到ice_candidate',);
  206. this.logger.log('server get ice_candidate', JSON.stringify(candidate));
  207. this.peer.addRemoteCandidate(candidate.candidate, candidate.sdpMid);
  208. }
  209. @SubscribeMessage('answer')
  210. handerAnswer(client: any, payload: any) {
  211. const answer = Buffer.from(payload, 'base64').toString('utf-8');
  212. console.log('answer', answer);
  213. const clientAnswer = JSON.parse(answer);
  214. this.peer.setLocalDescription(clientAnswer.sdp);
  215. this.peer.setRemoteDescription(clientAnswer.sdp, clientAnswer.type);
  216. }
  217. @SubscribeMessage('start')
  218. handlerWebrtcStart(client: any, payload: any) {
  219. console.log('start', payload);
  220. try {
  221. const obj = JSON.parse(payload);
  222. const requestPayLoad: InitRequest = Object.assign({}, obj, {
  223. user_id: this.user_id,
  224. roomId: this.roomId,
  225. });
  226. this.sceneService.init(requestPayLoad);
  227. this.logger.log(
  228. 'start and send to gprc sceneService,method=>init',
  229. JSON.stringify(requestPayLoad),
  230. );
  231. const startReply = {
  232. id: 'start',
  233. data: '{"IsHost":false,"SkinID":"10089","SkinDataVersion":"1008900008","RoomTypeID":""}',
  234. room_id: 'e629ef3e-022d-4e64-8654-703bb96410eb',
  235. channel_id: '3a1a62e9a3c74de6___channel',
  236. user_id: 'ed58c8d4ce38c',
  237. trace_id: '394df10a-d924-43a9-940d-1dbb41e43f24',
  238. packet_id: '',
  239. session_id: '67087ad820ea4c89af311e27281d73a6',
  240. client_os: '',
  241. fe_version: '',
  242. };
  243. this.startstreamingSub = this.sceneService.startSteaming.subscribe((val) => {
  244. if (val) {
  245. console.log('onSteaming-start', val);
  246. client.send(JSON.stringify(startReply));
  247. }
  248. // debugger
  249. });
  250. } catch (error) { }
  251. }
  252. handleConnection(client: WebSocket, ...args: any[]) {
  253. const { url } = args[0];
  254. console.log('url', url);
  255. const params = new URLSearchParams(url.replace('/ws?', ''));
  256. console.log('useId', params.get('userId'));
  257. console.log('roomId', params.get('roomId'));
  258. this.user_id = params.get('userId');
  259. this.roomId = params.get('roomId');
  260. this.sceneService.setConfig(this.user_id, this.roomId);
  261. this.logger.log(`Client connected:`);
  262. const connected = {
  263. channel_id: '',
  264. client_os: '',
  265. data: '',
  266. fe_version: '',
  267. id: 'init',
  268. packet_id: '',
  269. room_id: '',
  270. session_id: '',
  271. trace_id: '',
  272. user_id: '',
  273. };
  274. const tt = JSON.stringify(connected);
  275. client.send(tt);
  276. }
  277. handleDisconnect(client: WebSocket) {
  278. this.logger.log(`Client disconnected: ${client.id}`);
  279. this.peer && this.peer.close();
  280. this.startstreamingSub & this.startstreamingSub.unsubscribe();
  281. }
  282. }