client.js 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /* eslint-disable @typescript-eslint/no-var-requires */
  2. const nodeDataChannel = require('../../lib/index');
  3. const WebSocket = require('ws');
  4. const readline = require('readline');
  5. // Init Logger
  6. nodeDataChannel.initLogger('Error');
  7. // PeerConnection Map
  8. const pcMap = {};
  9. // Local ID
  10. const id = randomId(4);
  11. // Signaling Server
  12. const WS_URL = process.env.WS_URL || 'ws://localhost:8000';
  13. const ws = new WebSocket(WS_URL + '/' + id, {
  14. perMessageDeflate: false,
  15. });
  16. console.log(`The local ID is: ${id}`);
  17. console.log(`Waiting for signaling to be connected...`);
  18. ws.on('open', () => {
  19. console.log('WebSocket connected, signaling ready');
  20. readUserInput();
  21. });
  22. ws.on('error', (err) => {
  23. console.log('WebSocket Error: ', err);
  24. });
  25. ws.on('message', (msgStr) => {
  26. msg = JSON.parse(msgStr);
  27. switch (msg.type) {
  28. case 'offer':
  29. createPeerConnection(msg.id);
  30. pcMap[msg.id].setRemoteDescription(msg.description, msg.type);
  31. break;
  32. case 'answer':
  33. pcMap[msg.id].setRemoteDescription(msg.description, msg.type);
  34. break;
  35. case 'candidate':
  36. pcMap[msg.id].addRemoteCandidate(msg.candidate, msg.mid);
  37. break;
  38. default:
  39. break;
  40. }
  41. });
  42. function readUserInput() {
  43. // Read Line Interface
  44. const rl = readline.createInterface({
  45. input: process.stdin,
  46. output: process.stdout,
  47. });
  48. rl.question('Enter a remote ID to send an offer:\n', (peerId) => {
  49. if (peerId && peerId.length > 2) {
  50. console.log('Offering to ', peerId);
  51. createPeerConnection(peerId);
  52. console.log('Creating DataChannel with label "test"');
  53. let dc = pcMap[peerId].createDataChannel('test');
  54. dc.onOpen(() => {
  55. dc.sendMessage('Hello from ' + id);
  56. });
  57. dc.onMessage((msg) => {
  58. console.log('Message from ' + peerId + ' received:', msg);
  59. });
  60. }
  61. rl.close();
  62. readUserInput();
  63. });
  64. }
  65. function createPeerConnection(peerId) {
  66. // Create PeerConnection
  67. let peerConnection = new nodeDataChannel.PeerConnection('pc', { iceServers: ['stun:stun.l.google.com:19302'] });
  68. peerConnection.onStateChange((state) => {
  69. console.log('State: ', state);
  70. });
  71. peerConnection.onGatheringStateChange((state) => {
  72. console.log('GatheringState: ', state);
  73. });
  74. peerConnection.onLocalDescription((description, type) => {
  75. ws.send(JSON.stringify({ id: peerId, type, description }));
  76. });
  77. peerConnection.onLocalCandidate((candidate, mid) => {
  78. ws.send(JSON.stringify({ id: peerId, type: 'candidate', candidate, mid }));
  79. });
  80. peerConnection.onDataChannel((dc) => {
  81. console.log('DataChannel from ' + peerId + ' received with label "', dc.getLabel() + '"');
  82. dc.onMessage((msg) => {
  83. console.log('Message from ' + peerId + ' received:', msg);
  84. });
  85. dc.sendMessage('Hello From ' + id);
  86. });
  87. pcMap[peerId] = peerConnection;
  88. }
  89. function randomId(length) {
  90. var result = '';
  91. var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  92. var charactersLength = characters.length;
  93. for (var i = 0; i < length; i++) {
  94. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  95. }
  96. return result;
  97. }