meta.gateway.ts 9.6 KB

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