PageRenderTime 58ms CodeModel.GetById 12ms app.highlight 40ms RepoModel.GetById 1ms app.codeStats 0ms

/demos/client-side-socket-io.html

https://github.com/evenisse/WebRTC-Experiment
HTML | 221 lines | 180 code | 38 blank | 3 comment | 0 complexity | 222552fd502be2b530ce57a36ed311ec MD5 | raw file
  1<title>Simple client-side WebRTC Experiment using Socket.io over PubNub ® Muaz Khan</title>
  2<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  3
  4<h1>Simple client-side WebRTC Experiment using Socket.io over PubNub</h1>
  5
  6<meta name="description" content="A client side WebRTC experiment/demo using socket.io over pubnub! It is simple. It is included here for newcomers who are interested to learn WebRTC from demos!">
  7<link rel="author" type="text/html" href="https://plus.google.com/100325991024054712503">
  8<meta name="author" content="Muaz Khan">
  9
 10<style>@font-face { font-family: 'Open Sans'; font-style: normal; font-weight: 300; src: local('Open Sans Light'), local('OpenSans-Light'), url(/images/font.woff) format('woff'); } html { background: #ECECEC; font-family: 'Open Sans'; } body { color: #333; font: 1.4em 'Open Sans' , arial, sans-serif; font-weight: 300; line-height: 1.5; margin: 0 3em; background: white; border: 1px dotted #BBA9A9; border-top: 0; } h1, h2 { color: #2778ec; font-size: 1.6em; font-weight: 300; line-height: 1.15; }  a { display: inline-block; padding: 0.2em; color: #1B75C9; text-decoration: none; border-bottom: 1px dotted #0085FF; margin: 0 .2em; } a:hover { color: red; }</style>
 11
 12<div style="position: absolute;background: white;display: block; padding: 5px 10px;z-index: 100;">
 13    <a href="/">Home</a>
 14    » <a href="https://github.com/muaz-khan/WebRTC-Experiment/blob/master/demos/client-side-socket-io.html">Source Code</a>
 15</div>
 16
 17<script>
 18    function uniqueToken() {
 19        var s4 = function () {
 20            return Math.floor(Math.random() * 0x10000).toString(16);
 21        };
 22        return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
 23    }
 24    var uniqueChannel = uniqueToken();
 25</script>
 26
 27<script src="/lib/RTCPeerConnection-v1.4.js"></script>
 28<script src="/dependencies/socket.io.js"></script>
 29
 30<style>body{text-align: center;}</style>
 31<h2>Client video</h2>
 32<video id="client-video" autoplay></video>
 33
 34<h2>Remote video / Getting stream from peer2</h2>
 35<video id="remote-video-1" autoplay></video>
 36
 37<h2>Remote video / Getting stream from peer1</h2>
 38<video id="remote-video-2" autoplay></video>
 39
 40<!-- First of all; get camera -->
 41<script>
 42    var socket;
 43    function openSocket() {
 44		socket = io.connect('https://pubsub.pubnub.com/' + uniqueChannel, {
 45            channel: uniqueChannel,
 46            publish_key: 'pub-c-1ebf6bf7-3679-4964-b230-522d8684d071',
 47			subscribe_key: 'sub-c-da9eab08-7263-11e2-8b02-12313f022c90',
 48            ssl: true
 49        });
 50
 51        socket.on('message', function (message) {
 52
 53            if (message.firstPart || message.secondPart || message.thirdPart) {
 54                if (message.firstPart) {
 55                    global.firstPart = message.firstPart;
 56                    if (global.secondPart && global.thirdPart) processReceievdSDP(message.by);
 57                }
 58                if (message.secondPart) {
 59                    global.secondPart = message.secondPart;
 60                    if (global.firstPart && global.thirdPart) processReceievdSDP(message.by);
 61                }
 62
 63                if (message.thirdPart) {
 64                    global.thirdPart = message.thirdPart;
 65                    if (global.firstPart && global.secondPart) processReceievdSDP(message.by);
 66                }
 67            }
 68
 69            if (message.candidate) {
 70                /* 2nd peer should process/add ice candidates sent by 1st peer! */
 71                if (message.by == 'peer1') {
 72                    peer2 && peer2.addICE({
 73                        sdpMLineIndex: message.sdpMLineIndex,
 74                        candidate: JSON.parse(message.candidate)
 75                    });
 76                }
 77                else {
 78                    peer1 && peer1.addICE({
 79                        sdpMLineIndex: message.sdpMLineIndex,
 80                        candidate: JSON.parse(message.candidate)
 81                    });
 82                }
 83            }
 84        });
 85
 86        socket.on('connect', function () {
 87            /* Socket opened; Now start creating offer sdp */
 88            create1stPeer();
 89        });
 90    }
 91	
 92	function processReceievdSDP(by)
 93	{
 94		if (by == 'peer1') {
 95			offerSDP = JSON.parse(global.firstPart + global.secondPart + global.thirdPart);
 96			setTimeout(create2ndPeer, 400);
 97		}
 98		
 99		/* 1st peer should complete the handshake using answer SDP provided by 2nd peer! */
100		else peer1.addAnswerSDP(JSON.parse(global.firstPart + global.secondPart + global.thirdPart));
101	}
102
103    getUserMedia({
104        video: document.getElementById('client-video'),
105        onsuccess: function (stream) {
106            clientStream = stream;
107
108            openSocket();
109        },
110        onerror: function () {
111            alert('Either you not allowed access to your microphone/webcam or another application already using it.');
112        }
113    });
114    
115    var clientStream;
116
117    var global = {};
118</script>
119
120<!-- First peer: the offerer -->
121<script>
122    /* "offerSDP" will be used by your participant! */
123    var offerSDP, peer1;
124
125    function create1stPeer() {
126        var offerConfig = {
127            onOfferSDP: function (sdp) {
128                console.log('1st peer: offer sdp: ' + sdp);
129
130                /* Transmit offer SDP toward 2nd peer */
131                sendsdp(sdp, 'peer1');
132            },
133            onICE: function (candidate) {
134                console.log('1st peer: candidate' + candidate);
135
136                socket.send({
137                    by: 'peer1',
138                    sdpMLineIndex: candidate.sdpMLineIndex,
139                    candidate: JSON.stringify(candidate.candidate)
140                });
141            },
142            onRemoteStream: function (stream) {
143                console.log('1st peer: Wow! Got remote stream!');
144                var video = document.getElementById('remote-video-1');
145				if (!navigator.mozGetUserMedia) video.src = URL.createObjectURL(stream);
146				else video.mozSrcObject = stream;
147				video.play();
148            },
149            attachStream: clientStream
150        };
151
152        peer1 = RTCPeerConnection(offerConfig);
153    }
154</script>
155
156<!-- Second peer: the participant -->
157<script>
158
159    var peer2;
160
161    function  create2ndPeer() {
162        var answerConfig = {
163            onAnswerSDP: function (sdp) {
164                console.log('2nd peer: sdp' + sdp);
165
166                /* Transmit answer SDP toward 1st peer */
167                sendsdp(sdp, 'peer2');
168            },
169            onICE: function (candidate) {
170                console.log('2nd peer: candidate' + candidate);
171
172                socket.send({
173                    by: 'peer2',
174                    sdpMLineIndex: candidate.sdpMLineIndex,
175                    candidate: JSON.stringify(candidate.candidate)
176                });
177            },
178            onRemoteStream: function (stream) {
179                console.log('2nd peer: Wow! Got remote stream!');
180                var video = document.getElementById('remote-video-2');
181				if (!navigator.mozGetUserMedia) video.src = URL.createObjectURL(stream);
182				else video.mozSrcObject = stream;
183				video.play();
184            },
185            attachStream: clientStream,
186
187            /* You'll use offer SDP here */
188            offerSDP: offerSDP
189        };
190        peer2 = RTCPeerConnection(answerConfig);
191    }
192
193    function sendsdp(sdp, by) {
194        sdp = JSON.stringify(sdp);
195            var part = parseInt(sdp.length / 3);
196
197            var firstPart = sdp.slice(0, part),
198                secondPart = sdp.slice(part, sdp.length - 1),
199                thirdPart = '';
200
201            if (sdp.length > part + part) {
202                secondPart = sdp.slice(part, part + part);
203                thirdPart = sdp.slice(part + part, sdp.length);
204            }
205
206            socket.send({
207                by: by,
208                firstPart: firstPart
209            });
210
211            socket.send({
212                by: by,
213                secondPart: secondPart
214            });
215
216            socket.send({
217                by: by,
218                thirdPart: thirdPart
219            });
220    }
221</script>