Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

javascript - Webrtc Video Call Fail Outside Local Network using Simple Peer Library in Reacjs Project

I am facing problem With connecting with other peers over different Internets I have researched on it and found stun and turn Server Is needed I don't know about turn and stun server.is turn server is free and where do I get turn server. Kindly Help Me in this I am very thankfull to you

Here Below NodeJs server-side Code

require('dotenv').config();
    const http = require('http');
    const express = require('express');
    const socketio = require('socket.io');
    const cors = require('cors');
    const { addUser, removeUser, getUser, getUsersInRoom } = require('./users');

const router = require('./router');

const app = express();
const server = http.createServer(app);
const io = socketio(server);
let Userss={};
let VideoRoomUsers={};
const socketToRoom = {};
app.use(cors());
app.use(router);
socket.on("join room", roomID => {
 if (VideoRoomUsers[roomID]) {
   const length = VideoRoomUsers[roomID].length;
   if (length === 4) {
      socket.emit("room full");
      return;
   }
  VideoRoomUsers[roomID].push(socket.id);
 } else {
  VideoRoomUsers[roomID] = [socket.id];
}
socketToRoom[socket.id] = roomID;
const usersInThisRoom = VideoRoomUsers[roomID].filter(id => id !== socket.id);
console.log(usersInThisRoom);
socket.emit("all users", usersInThisRoom);
});

socket.on("sending signal", payload => {
 io.to(payload.userToSignal).emit('user joined', { signal: payload.signal, callerID: 
  payload.callerID });
});

socket.on("returning signal", payload => {
 io.to(payload.callerID).emit('receiving returned signal', { signal: payload.signal, id: 
 socket.id });
});
 socket.on('disconnect', () => {

   const roomID = socketToRoom[socket.id];
   let room = VideoRoomUsers[roomID];
   if (room) {
      room = room.filter(id => id !== socket.id);
      VideoRoomUsers[roomID] = room;
    }
   })
});
const port=process.env.PORT || 5000
server.listen(port, () => console.log(`Server has started. on port ${port}`));

Below Is My Video Calling Room Reactjs Code I have hosted server on heroku as well socketurl is Heroku deployed nodejs project url

import React, { useEffect, useRef, useState } from "react";
import io from "socket.io-client";
import Peer from "simple-peer";
import "./room.css";

const Video = (props) => {
  const ref = useRef();

  useEffect(() => {
    props.peer.on("stream", (stream) => {
      ref.current.srcObject = stream;
    });
  }, []);

  return <video className={"mini-video"} playsInline autoPlay ref={ref} />;
};

const Room = (props) => {
  const [peers, setPeers] = useState([]);
  const socketRef = useRef();
  const userVideo = useRef();
  const peersRef = useRef([]);
  const roomID = props.match.params.roomID;
  // server running on heroku url is https://videogroup.herokuapp.com/
  console.log(roomID);
  useEffect(() => {
    socketRef.current = io("https://webrtcserverr.herokuapp.com/");
    navigator.mediaDevices
      .getUserMedia({ video: true, audio: true })
      .then((stream) => {
        userVideo.current.srcObject = stream;
        socketRef.current.emit("join room", roomID);
        socketRef.current.on("all users", (users) => {
          const peers = [];
          users.forEach((userID) => {
            const peer = createPeer(userID, socketRef.current.id, stream);
            peersRef.current.push({
              peerID: userID,
              peer,
            });
            peers.push(peer);
          });
          setPeers(peers);
        });

        socketRef.current.on("user joined", (payload) => {
          const peer = addPeer(payload.signal, payload.callerID, stream);
          peersRef.current.push({
            peerID: payload.callerID,
            peer,
          });

          setPeers((users) => [...users, peer]);
        });

        socketRef.current.on("receiving returned signal", (payload) => {
          const item = peersRef.current.find((p) => p.peerID === payload.id);
          item.peer.signal(payload.signal);
        });
      });
  }, []);

  function createPeer(userToSignal, callerID, stream) {
    const peer = new Peer({
      initiator: true,
      trickle: false,
      config: {
        iceServers: [
          { urls: "stun:stun.l.google.com:19302" },
          { urls: "stun:global.stun.twilio.com:3478?transport=udp" },
        ],
      },
      stream,
    });

    peer.on("signal", (signal) => {
      socketRef.current.emit("sending signal", {
        userToSignal,
        callerID,
        signal,
      });
    });

    return peer;
  }

  function addPeer(incomingSignal, callerID, stream) {
    const peer = new Peer({
      initiator: false,
      trickle: false,
      config: {
        iceServers: [
          {
            urls: "stun:stun.stunprotocol.org",
          },
          {
            urls: "turn:numb.viagenie.ca",
            credential: "muazkh",
            username: "webrtc@live.com",
          },
        ],
      },
      stream,
    });

    peer.on("signal", (signal) => {
      socketRef.current.emit("returning signal", { signal, callerID });
    });

    peer.signal(incomingSignal);

    return peer;
  }

  return (
    <div>
      <div className={"video-container"}>
        <video ref={userVideo} autoPlay playsInline />
      </div>
      <div className={"mini-video-container"}>
        {peers.map((peer, index) => {
          return <Video key={index} peer={peer} />;
        })}
      </div>
    </div>
  );
};

export default Room;
question from:https://stackoverflow.com/questions/65901121/webrtc-video-call-fail-outside-local-network-using-simple-peer-library-in-reacjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...