Created
August 27, 2018 13:47
-
-
Save dolegi/e94721b1118e0c09bb15c987b88bc9b2 to your computer and use it in GitHub Desktop.
Web RTC example
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
const webrtc = require('wrtc'); | |
const lzString = require('lz-string'); | |
const readline = require('readline'); | |
const dataChannelSettings = { | |
reliable: { | |
ordered: true, | |
maxRetransmits: 1 | |
} | |
} | |
const pcSettings = [ | |
{ | |
iceServers: [{ url: 'stun:stun.l.google.com:19302'}] | |
}, | |
{ | |
optional: [{ DtlsSrtpKeyAgreement: false }] | |
} | |
] | |
let pc | |
const pendingDataChannels = {} | |
const dataChannels = {} | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}) | |
if (process.argv[2] === 'create') { | |
makeOffer() | |
} else { | |
rl.question('Offer:\n', offer => { | |
getOffer(offer) | |
}) | |
} | |
function makeOffer() { | |
pc = new webrtc.RTCPeerConnection(pcSettings) | |
makeDataChannel() | |
pc.createOffer(desc => pc.setLocalDescription(desc, () => {}, err => {}), | |
err => console.log("Error ", err)) | |
pc.onicecandidate = candidate => { | |
if (candidate.candidate == null) { | |
console.log("Your offer is:") | |
console.log(JSON.stringify(pc.localDescription)) | |
const answer = new webrtc.RTCSessionDescription(pc.localDescription); | |
answer.type = 'offer' | |
pc.setRemoteDescription(answer); | |
} | |
} | |
} | |
function makeDataChannel() { | |
const channel = pc.createDataChannel('test', { reliable:true }) | |
channel.onopen = () => { | |
console.log("\nConnected!"); | |
inputLoop(channel); | |
} | |
channel.onmessage = evt => { | |
{ message } = JSON.parse(evt.data) | |
console.log(message) | |
inputLoop(channel) | |
}; | |
} | |
function inputLoop(channel) { | |
rl.question("> ", text => { | |
channel.send(JSON.stringify({ message: text })); | |
inputLoop(channel); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment