0

我正在开发一个具有 Twilio Video 并使用 Websocket 和 RTC 数据通道的反应项目。一切都在我的本地网络上运行,但是当我将其部署到 AWS ec2 时,RTC 数据通道无法通过信令服务器相互传输数据。请提出我错的地方我已经在我的本地网络上用 3 台不同的电脑测试了我的应用程序,它正在本地网络上工作,比如通过 WebSocket 信号通过 RTC 数据通道和 Twilio 视频流传输数据

这是我的 Client.js

const MESSAGE_TYPE = { SDP: 'SDP', CANDIDATE: 'CANDIDATE' }

  let code;
  let peerConnection;
  let signaling;

  const initScreenStreaming = useCallback( () => {
    try {
      signaling = new WebSocket("wss://call.lothamer.com:9000");
      peerConnection = createPeerConnection();
      addMessageHandler();
    } catch (err) {
      console.error(err);
    }
  },[]);


  const createPeerConnection = useCallback( () => {
    
    let config={"iceServers":[{"urls":["stun:stun.l.google.com:19302"]}],"iceTransportPolicy":"all","iceCandidatePoolSize":"0"}
    const pc = new RTCPeerConnection(config);

    pc.onnegotiationneeded = async () => {
      await createAndSendOffer();
    };

    pc.onicecandidate = (iceEvent) => {
      console.log('__onicecandidate__');
      if (iceEvent && iceEvent.candidate) {
        sendMessage({
          message_type: MESSAGE_TYPE.CANDIDATE,
          content: iceEvent.candidate,
        });
      }
    };

    pc.ondatachannel = (event) => {
      const { channel } = event;
      channel.binaryType = 'arraybuffer';
      channel.onmessage = async (event) => {
        const { data } = event;
        try { 
          let dataTypeObject = JSON.parse(data);
          if( dataTypeObject.iframeURL === true ){
            setiframeUrlAddressBar(dataTypeObject.url);
          }else if( dataTypeObject.signature === true ){  
            handleSignaturePopupOpen();          
          }else if(dataTypeObject.shared === true){           
              handleScreenShareStart();                     
          }else if( dataTypeObject.shared === false ){
              handleScreenShareStop();
          }else{
            setOtherPCMousePostionX(dataTypeObject.mousePonterX);
            setOtherPCMousePostionY(dataTypeObject.mousePonterY);
            if( dataTypeObject.viewType === 2 ){
              handleOtherScreenScreenData(dataTypeObject.screen);
            }
          }              
          channel.close();          
        } catch (err) {
          console.log(`${texts.CO_BROWSING_FAILE_ERROR_HELP_TEXT} : ${err}`);
        }
      };
    };
    return pc;
  }, []);

  const addMessageHandler = useCallback( () => {
    signaling.onopen = () => {
      console.log('Signaling open');
      signaling.send(JSON.stringify({ type: 'welcome' }));
  }
    signaling.onmessage = async (message) => {
      const data = JSON.parse(message.data);
      if (!data) {
        return;
      }
      const { message_type, content } = data;
      try {
        if (message_type === MESSAGE_TYPE.CANDIDATE && content) {
          await peerConnection.addIceCandidate(content);
        } else if (message_type === MESSAGE_TYPE.SDP) {
          if (content.type === 'offer') {
            await peerConnection.setRemoteDescription(content);
            const answer = await peerConnection.createAnswer();
            await peerConnection.setLocalDescription(answer);
            sendMessage({
              message_type: MESSAGE_TYPE.SDP,
              content: answer,
            });
          } else if (content.type === 'answer') {
            await peerConnection.setRemoteDescription(content);
          } else {
            console.log(texts.SIGNALING_ERROR);
          }
        }
      } catch (err) {
        console.error(err);
      }
    }
  },[]);


  const sendMessage = useCallback( (message) => {
    console.log('Signaling ____'+JSON.stringify(signaling));
    if( signaling.readyState === 1 ){
      signaling.send(JSON.stringify({
        ...message,
        code,
      })); 
    }   
  },[]);

  const createAndSendOffer = useCallback( async () => {
    const offer = await peerConnection.createOffer();
    await peerConnection.setLocalDescription(offer);
    sendMessage({
      message_type: MESSAGE_TYPE.SDP,
      content: offer,
    });
  }, [] );

  const shareDataViaRTC = useCallback( (data = { type : "welcome" }) => {
      const channelLabel = 'lvc123';
      const channel = peerConnection.createDataChannel(channelLabel);
      console.log(channel);
      //channel.binaryType = 'arraybuffer'; 
      channel.onopen = async () => {  
        console.log('___Channel Open___');      
        channel.send(JSON.stringify(data));        
      };
      channel.onclose = () => {
        console.log(texts.CHANNEL_CLOSE);
      };    
  },[]);

这是 serevr.js

const { videoToken } = require('./tokens');
const bodyParser = require('body-parser');
const pino = require('express-pino-logger')();
const express = require('express');
const https = require('https');
const WebSocket = require('ws');
const path = require('path');
const fs = require('fs');
require('dotenv').config();
var cors = require('cors');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
app.use(cors());

const sendTokenResponse = (token, res) => {
  res.set('Content-Type', 'application/json');
  res.send(
    JSON.stringify({
      token: token.toJwt()
    })
  );
};

app.use(express.static(path.join(__dirname+'/../', 'build')));

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname+'/../', 'build', 'index.html'));
});


app.get('/video/token', (req, res) => {
  const identity = req.query.identity;
  const room = req.query.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);

});

app.post('/video/token', (req, res) => {
  const identity = req.body.identity;
  const room = req.body.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

//ssl keypair
const options = {
  key: fs.readFileSync(process.env.NODE_SSL_KEY),
  cert: fs.readFileSync(process.env.NODE_SSL_CERT)
};

// Create https server and run it.
const server = https.createServer( options, app );

const wss = new WebSocket.Server({ server});

console.log("started web socket server...")

wss.on('open', function open() {
  console.log('connected');
  ws.send(Date.now());
});

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {

    // sends the data to all connected clients
    wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN) {
          client.send(message);
        }
    });
  });
});

const port = process.env.NODE_SERVER_PORT || 9000;
server.listen(port, function() {
  console.log('Express server running on port :' + port);
});```

4

0 回答 0