meta.gateway.ts 9.8 KB

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