Advertisement
Guest User

Untitled

a guest
Aug 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. import React, { Component } from 'react';
  4. import {
  5.   AppRegistry,
  6.   StyleSheet,
  7.   Text,
  8.   TouchableHighlight,
  9.   View,
  10.   TextInput,
  11.   ListView,
  12.   Platform,
  13. } from 'react-native';
  14.  
  15. import io from 'socket.io-client';
  16.  
  17. const socket = io.connect('http://192.168.1.2:3000', {transports: ['websocket']});
  18. console.log(1)
  19. import {
  20.   RTCPeerConnection,
  21.   RTCMediaStream,
  22.   RTCIceCandidate,
  23.   RTCSessionDescription,
  24.   RTCView,
  25.   MediaStreamTrack,
  26.   getUserMedia,
  27. } from 'react-native-webrtc';
  28.  
  29. const configuration = {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]};
  30.  
  31. const pcPeers = {};
  32. let localStream;
  33.  
  34. function getLocalStream(callback) {
  35.  
  36.   getUserMedia({
  37.     audio: true,
  38.     video: false,
  39.   }, function (stream) {
  40.     console.log('getUserMedia success', stream);
  41.     callback(stream);
  42.   }, logError);
  43. }
  44.  
  45. function join(roomID) {
  46.   socket.emit('join', roomID, function(data){
  47.     console.log('join', data, socket.id);
  48.     container.setState({ masterId: data.master });
  49.  
  50.     let isMaster = false;
  51.     if(data.master === socket.id) {
  52.       isMaster = true;
  53.       container.setState({ isMaster });
  54.     }
  55.     for(let socketId of data.socketIds) {
  56.       createPC(socketId, true, isMaster);
  57.     }
  58.   });
  59. }
  60.  
  61. function createPC(socketId, isOffer, isMaster) {
  62.   const pc = new RTCPeerConnection(configuration);
  63.   pcPeers[socketId] = pc;
  64.  
  65.   pc.onicecandidate = function (event) {
  66.     console.log('onicecandidate', event.candidate);
  67.     if (event.candidate) {
  68.       socket.emit('exchange', {'to': socketId, 'candidate': event.candidate });
  69.     }
  70.   };
  71.  
  72.   function createOffer() {
  73.     pc.createOffer(function(desc) {
  74.       console.log('createOffer', desc);
  75.       pc.setLocalDescription(desc, function () {
  76.         console.log('setLocalDescription', pc.localDescription);
  77.         socket.emit('exchange', {'to': socketId, 'sdp': pc.localDescription });
  78.       }, logError);
  79.     }, logError);
  80.   }
  81.  
  82.   pc.onnegotiationneeded = function () {
  83.     console.log('onnegotiationneeded');
  84.     if (isOffer) {
  85.       createOffer();
  86.     }
  87.   }
  88.  
  89.   pc.oniceconnectionstatechange = function(event) {
  90.     console.log('oniceconnectionstatechange', event.target.iceConnectionState);
  91.     if (event.target.iceConnectionState === 'completed') {
  92.       setTimeout(() => {
  93.         getStats();
  94.       }, 1000);
  95.     }
  96.     if (event.target.iceConnectionState === 'connected') {
  97.       createDataChannel();
  98.     }
  99.   };
  100.   pc.onsignalingstatechange = function(event) {
  101.     console.log('onsignalingstatechange', event.target.signalingState);
  102.   };
  103.  
  104.   pc.onaddstream = function (event) {
  105.     console.log('onaddstream', event.stream);
  106.     container.setState({info: 'One peer join!'});
  107.  
  108.     const remoteList = container.state.remoteList;
  109.     remoteList[socketId] = event.stream.toURL();
  110.     container.setState({ remoteList: remoteList });
  111.    
  112.     if(!container.state.isMaster) {
  113.       container.setState({ masterURL: remoteList[container.state.masterId]})
  114.     }
  115.   };
  116.   pc.onremovestream = function (event) {
  117.     console.log('onremovestream', event.stream);
  118.   };
  119.  
  120.   getLocalStream(function(stream) {
  121.     localStream = stream;
  122.     pc.addStream(localStream);
  123.   });
  124.  
  125.  
  126.   function createDataChannel() {
  127.     if (pc.textDataChannel) {
  128.       return;
  129.     }
  130.     const dataChannel = pc.createDataChannel("text");
  131.  
  132.     dataChannel.onerror = function (error) {
  133.       console.log("dataChannel.onerror", error);
  134.     };
  135.  
  136.     dataChannel.onmessage = function (event) {
  137.       console.log("dataChannel.onmessage:", event.data);
  138.       container.receiveTextData({user: socketId, message: event.data});
  139.     };
  140.  
  141.     dataChannel.onopen = function () {
  142.       console.log('dataChannel.onopen');
  143.       container.setState({textRoomConnected: true});
  144.     };
  145.  
  146.     dataChannel.onclose = function () {
  147.       console.log("dataChannel.onclose");
  148.     };
  149.  
  150.     pc.textDataChannel = dataChannel;
  151.   }
  152.   return pc;
  153. }
  154.  
  155. function exchange(data) {
  156.   const fromId = data.from;
  157.   let pc;
  158.   if (fromId in pcPeers) {
  159.     pc = pcPeers[fromId];
  160.   } else {
  161.     pc = createPC(fromId, false);
  162.   }
  163.  
  164.   if (data.sdp) {
  165.     console.log('exchange sdp', data);
  166.     pc.setRemoteDescription(new RTCSessionDescription(data.sdp), function () {
  167.       if (pc.remoteDescription.type == "offer")
  168.         pc.createAnswer(function(desc) {
  169.           console.log('createAnswer', desc);
  170.           pc.setLocalDescription(desc, function () {
  171.             console.log('setLocalDescription', pc.localDescription);
  172.             socket.emit('exchange', {'to': fromId, 'sdp': pc.localDescription });
  173.           }, logError);
  174.         }, logError);
  175.     }, logError);
  176.   } else {
  177.     console.log('exchange candidate', data);
  178.     pc.addIceCandidate(new RTCIceCandidate(data.candidate));
  179.   }
  180. }
  181.  
  182. function leave(socketId) {
  183.   console.log('leave', socketId);
  184.   const pc = pcPeers[socketId];
  185.   const viewIndex = pc.viewIndex;
  186.   pc.close();
  187.   delete pcPeers[socketId];
  188.  
  189.   const remoteList = container.state.remoteList;
  190.   delete remoteList[socketId]
  191.   container.setState({ remoteList: remoteList });
  192.   container.setState({info: 'One peer leave!'});
  193. }
  194. socket.on('connect_error', (e)=>{
  195.   console.log(2)
  196.   console.log(e)
  197. })
  198. socket.on('exchange', function(data){
  199.   exchange(data);
  200. });
  201. socket.on('leave', function(socketId){
  202.   leave(socketId);
  203. });
  204.  
  205. socket.on('connect', function(data) {
  206.   console.log('connect');
  207.   container.setState({status: 'ready', info: 'Please enter or create room ID'});
  208. });
  209.  
  210. function logError(error) {
  211.   console.log("logError", error);
  212. }
  213.  
  214. function mapHash(hash, func) {
  215.   const array = [];
  216.   for (const key in hash) {
  217.     const obj = hash[key];
  218.     array.push(func(obj, key));
  219.   }
  220.   return array;
  221. }
  222.  
  223. function getStats() {
  224.   const pc = pcPeers[Object.keys(pcPeers)[0]];
  225.   if (pc.getRemoteStreams()[0] && pc.getRemoteStreams()[0].getAudioTracks()[0]) {
  226.     const track = pc.getRemoteStreams()[0].getAudioTracks()[0];
  227.     console.log('track', track);
  228.     pc.getStats(track, function(report) {
  229.       console.log('getStats report', report);
  230.     }, logError);
  231.   }
  232. }
  233.  
  234. let container;
  235.  
  236. const RCTWebRTCDemo = React.createClass({
  237.   getInitialState: function() {
  238.     this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => true});
  239.     return {
  240.       info: 'Initializing',
  241.       status: 'init',
  242.       roomID: '',
  243.       isFront: true,
  244.       selfViewSrc: null,
  245.       remoteList: {},
  246.       textRoomConnected: false,
  247.       textRoomData: [],
  248.       textRoomValue: '',
  249.       isMaster: false,
  250.       masterURL: '',
  251.       masterId: '',
  252.     };
  253.   },
  254.   componentDidMount: function() {
  255.     container = this;
  256.   },
  257.   _press(event) {
  258.     this.refs.roomID.blur();
  259.     this.setState({status: 'connect', info: 'Connecting'});
  260.     join(this.state.roomID);
  261.   },
  262.  
  263.   receiveTextData(data) {
  264.     const textRoomData = this.state.textRoomData.slice();
  265.     textRoomData.push(data);
  266.     this.setState({textRoomData, textRoomValue: ''});
  267.   },
  268.   _textRoomPress() {
  269.     if (!this.state.textRoomValue) {
  270.       return
  271.     }
  272.     const textRoomData = this.state.textRoomData.slice();
  273.     textRoomData.push({user: 'Me', message: this.state.textRoomValue});
  274.     for (const key in pcPeers) {
  275.       const pc = pcPeers[key];
  276.       pc.textDataChannel.send(this.state.textRoomValue);
  277.     }
  278.     this.setState({textRoomData, textRoomValue: ''});
  279.   },
  280.   _renderTextRoom() {
  281.     return (
  282.       <View style={styles.listViewContainer}>
  283.         <ListView
  284.           dataSource={this.ds.cloneWithRows(this.state.textRoomData)}
  285.           renderRow={rowData => <Text>{`${rowData.user}: ${rowData.message}`}</Text>}
  286.           />
  287.         <TextInput
  288.           style={{width: 200, height: 30, borderColor: 'gray', borderWidth: 1}}
  289.           onChangeText={value => this.setState({textRoomValue: value})}
  290.           value={this.state.textRoomValue}
  291.         />
  292.         <TouchableHighlight
  293.           onPress={this._textRoomPress}>
  294.           <Text>Send</Text>
  295.         </TouchableHighlight>
  296.       </View>
  297.     );
  298.   },
  299.   render() {
  300.     return (
  301.       <View style={styles.container}>
  302.         <Text style={styles.welcome}>
  303.           {this.state.info}
  304.         </Text>
  305.         {this.state.textRoomConnected && this._renderTextRoom()}
  306.         <View style={{flexDirection: 'row'}}>
  307.           <Text>
  308.             {this.state.isMaster ? "Master" : "Slave"}
  309.           </Text>
  310.         </View>
  311.         { this.state.status == 'ready' ?
  312.           (<View>
  313.             <TextInput
  314.               ref='roomID'
  315.               autoCorrect={false}
  316.               style={{width: 200, height: 40, borderColor: 'gray', borderWidth: 1}}
  317.               onChangeText={(text) => this.setState({roomID: text})}
  318.               value={this.state.roomID}
  319.             />
  320.             <TouchableHighlight
  321.               onPress={this._press}>
  322.               <Text>Enter room</Text>
  323.             </TouchableHighlight>
  324.           </View>) : null
  325.         }
  326.       </View>
  327.     );
  328.   }
  329. });
  330.  
  331. const styles = StyleSheet.create({
  332.   selfView: {
  333.     width: 200,
  334.     height: 150,
  335.   },
  336.   remoteView: {
  337.     width: 200,
  338.     height: 150,
  339.   },
  340.   container: {
  341.     flex: 1,
  342.     justifyContent: 'center',
  343.     backgroundColor: '#F5FCFF',
  344.   },
  345.   welcome: {
  346.     fontSize: 20,
  347.     textAlign: 'center',
  348.     margin: 10,
  349.   },
  350.   listViewContainer: {
  351.     height: 150,
  352.   },
  353. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement