mirror of
https://github.com/giongto35/cloud-game.git
synced 2026-07-18 00:55:40 +00:00
106 lines
2.4 KiB
HTML
106 lines
2.4 KiB
HTML
<html>
|
|
|
|
<style>
|
|
textarea {
|
|
width: 60%;
|
|
height: 50px;
|
|
}
|
|
</style>
|
|
|
|
<div id="remoteVideos" ></div> <br />
|
|
<div>
|
|
Use Up, Down, Left, Right to Move <br />
|
|
Space to jump <br />
|
|
Ctrl to sprint <br />
|
|
Enter to select in menu <br />
|
|
|
|
Fullscreen media for better gaming experience<br />
|
|
</div>
|
|
|
|
<button id="playGame" onclick="window.startSession()" disabled> Play Mario </button>
|
|
<div id="div"></div>
|
|
|
|
<div>
|
|
Refresh to retry
|
|
</div>
|
|
<script>
|
|
|
|
var localSessionDescription = ""
|
|
var remoteSessionDescription = ""
|
|
|
|
function postSession(session) {
|
|
if (session == "") {
|
|
return;
|
|
}
|
|
var xhttp = new XMLHttpRequest();
|
|
xhttp.onreadystatechange = function() {
|
|
if (this.readyState == 4 && this.status == 200) {
|
|
remoteSessionDescription = this.responseText;
|
|
document.getElementById('playGame').disabled = false;
|
|
}
|
|
};
|
|
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));
|
|
localSessionDescription = 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 = remoteSessionDescription
|
|
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>
|