meta.gateway.ts 9.6 KB

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