Last active
July 28, 2019 11:40
-
-
Save gmarcos87/278f50f4562948685058cf6b6c890d6f to your computer and use it in GitHub Desktop.
WIP - Webrtc in a mesh network
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createConnection(){ | |
const connection = new RTCPeerConnection(); | |
let myIces = []; | |
let channel; | |
createChannel() | |
/** | |
* | |
* @param {String} type | |
* @param {String} sdp | |
* @param {RTCPeerConnection} peerConnection | |
*/ | |
async function tryConnection({type, sdp}, peerConnection) { | |
peerConnection.addEventListener('icecandidate', async ({candidate}) => { | |
if (candidate) { | |
myIces = [...myIces, candidate] | |
console.log('local connection ICE candidate: ', JSON.stringify(candidate)); | |
console.log(myIces) | |
} | |
}); | |
let description; | |
if(type === 'offer') { | |
await peerConnection.setRemoteDescription({type, sdp}) | |
description = await peerConnection.createAnswer() | |
} else if (type === 'answer') { | |
await peerConnection.setRemoteDescription({type, sdp}) | |
return true; | |
} else { | |
description = await peerConnection.createOffer() | |
} | |
await peerConnection.setLocalDescription(description); | |
return description | |
} | |
/** | |
* | |
* @param {String} sdp | |
*/ | |
async function checkOffer(sdp) { | |
const answer = await tryConnection({type: 'offer', sdp}, connection); | |
console.log(JSON.stringify(answer.sdp)) | |
return answer; | |
} | |
async function makeOffer() { | |
await tryConnection({}, connection) | |
console.log(JSON.stringify(connection.localDescription.sdp)); | |
return connection.localDescription | |
} | |
/** | |
* | |
* @param {String} sdp | |
* @param {RTCIceCandidate} icecandidate | |
*/ | |
async function acceptAnswer(sdp, icecandidate) { | |
const res = tryConnection({ type: 'answer', sdp }, connection) | |
connection.addIceCandidate(icecandidate) | |
return res; | |
} | |
async function createChannel() { | |
channel = connection.createDataChannel('messaging-channel'); | |
channel.addEventListener('open', () => { | |
console.log('Local channel open!'); | |
}); | |
channel.addEventListener('close', () => { | |
console.log('Local channel closed!'); | |
}); | |
//Override channel it this is a answer connection | |
connection.ondatachannel = (remoteChannel) => channel = remoteChannel | |
} | |
return { | |
makeOffer, | |
checkOffer, | |
connection, | |
channel, | |
acceptAnswer, | |
getIces: () => myIces, | |
} | |
} | |
module.exports = createConnection |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment