|
@@ -0,0 +1,61 @@
|
|
|
+const socket = io('/')
|
|
|
+const videoGrid = document.getElementById('video-grid')
|
|
|
+let myPeer = null
|
|
|
+const myVideo = document.createElement('video')
|
|
|
+myVideo.muted = true
|
|
|
+const peers = {}
|
|
|
+navigator.mediaDevices.getUserMedia({
|
|
|
+ video: true,
|
|
|
+ audio: true
|
|
|
+}).then(stream => {
|
|
|
+ myPeer = new Peer(undefined, {
|
|
|
+ host: '/',
|
|
|
+ port: '4231'
|
|
|
+ })
|
|
|
+ addVideoStream(myVideo, stream)
|
|
|
+
|
|
|
+ myPeer.on('call', call => {
|
|
|
+ call.answer(stream)
|
|
|
+ })
|
|
|
+
|
|
|
+ myPeer.on('open', id => {
|
|
|
+ socket.emit('join-room', ROOM_ID, id)
|
|
|
+ })
|
|
|
+
|
|
|
+ socket.on('connected-clients', connectedClients => {
|
|
|
+ for (const userId in connectedClients) {
|
|
|
+ connectToNewUser(connectedClients[userId], stream)
|
|
|
+ }
|
|
|
+ })
|
|
|
+
|
|
|
+ socket.on('user-connected', userId => {
|
|
|
+ connectToNewUser(userId, stream)
|
|
|
+ })
|
|
|
+}).catch(error=>{
|
|
|
+ console.log("Error: ",error)
|
|
|
+})
|
|
|
+
|
|
|
+socket.on('user-disconnected', userId => {
|
|
|
+ if (peers[userId]) peers[userId].close()
|
|
|
+})
|
|
|
+
|
|
|
+function connectToNewUser(userId, stream) {
|
|
|
+ const call = myPeer.call(userId, stream)
|
|
|
+ const video = document.createElement('video')
|
|
|
+ call.on('stream', userVideoStream => {
|
|
|
+ addVideoStream(video, userVideoStream)
|
|
|
+ })
|
|
|
+ call.on('close', () => {
|
|
|
+ video.remove()
|
|
|
+ })
|
|
|
+
|
|
|
+ peers[userId] = call
|
|
|
+}
|
|
|
+
|
|
|
+function addVideoStream(video, stream) {
|
|
|
+ video.srcObject = stream
|
|
|
+ video.addEventListener('loadedmetadata', () => {
|
|
|
+ video.play()
|
|
|
+ })
|
|
|
+ videoGrid.append(video)
|
|
|
+}
|