cloud-game/index.html
2019-04-02 01:18:57 +08:00

96 lines
2.4 KiB
HTML

<html>
<style>
textarea {
width: 60%;
height: 50px;
}
</style>
<div id="remoteVideos" ></div> <br />
Browser base64 Session Description <br /><textarea id="localSessionDescription" readonly="true"></textarea> <br />
Golang base64 Session Description: <br /><textarea id="remoteSessionDescription"> </textarea> <br/>
<button onclick="window.startSession()"> Start Session </button>
<div id="div"></div>
<div>
Refresh to retry
</div>
<script>
function postSession(session) {
if (session == "") {
return;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('remoteSessionDescription').value = this.responseText;
}
};
xhttp.open("POST", "/session", true);
xhttp.setRequestHeader("Content-type", "text/plain");
xhttp.send(session);
}
let pc = new RTCPeerConnection({
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
})
let log = msg => {
document.getElementById('div').innerHTML += msg + '<br>'
}
let inputChannel = pc.createDataChannel('foo')
inputChannel.onclose = () => console.log('inputChannel has closed')
inputChannel.onopen = () => console.log('inputChannel has opened')
inputChannel.onmessage = e => log(`Message from DataChannel '${inputChannel.label}' payload '${e.data}'`)
pc.ontrack = function (event) {
var el = document.createElement(event.track.kind)
el.srcObject = event.streams[0]
el.autoplay = true
el.controls = true
document.getElementById('remoteVideos').appendChild(el)
}
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
pc.onicecandidate = event => {
if (event.candidate === null) {
var session = btoa(JSON.stringify(pc.localDescription));
document.getElementById('localSessionDescription').value = session;
postSession(session)
}
}
pc.createOffer({offerToReceiveVideo: true, offerToReceiveAudio: true}).then(d => pc.setLocalDescription(d)).catch(log)
document.body.onkeydown = function(e){
inputChannel.send(e.keyCode)
};
document.body.onkeyup = function(e){
inputChannel.send(-e.keyCode)
};
window.startSession = () => {
let sd = document.getElementById('remoteSessionDescription').value
if (sd === '') {
return alert('Session Description must not be empty')
}
try {
pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(sd))))
} catch (e) {
alert(e)
}
}
</script>
</html>