|
<!-- This is a Node+WebSocket powered demo to sync videos |
|
across different browsers. This file is the client, |
|
the other one is the Node server. Powered by Node and |
|
http://github.com/miksago/node-websocket-server --> |
|
|
|
<style> |
|
.inactive { display: none; } |
|
.active { display: block; } |
|
</style> |
|
<script> |
|
var controller = null; |
|
window.onload = function() { |
|
|
|
if ($_("#name").value == "") |
|
$_("#name").value = "user"+parseInt(99999*Math.random()); |
|
|
|
var conn; |
|
$_("#join").onclick = function() { |
|
conn = new WebSocket("ws://localhost:8000/test"); |
|
$_("#username").innerHTML = $_("#name").value |
|
$_("#room").className = "active"; |
|
$_("#registration").className = "inactive"; |
|
var video = $_("video"); |
|
video.addEventListener("timeupdate", function() { |
|
if (iAmControlling()) conn.send(video.currentTime); |
|
}, true); |
|
video.addEventListener("pause", function() { |
|
if (iAmControlling()) conn.send("pause "+video.currentTime); |
|
}, true); |
|
conn.onmessage = function (ev) { |
|
var matches; |
|
if (matches = ev.data.match(/^control (.+)$/)) { |
|
$_("#controller").innerHTML = matches[1]; |
|
} else if (matches = ev.data.match(/^userCount (.+)$/)) { |
|
// $_("#userCount").innerHTML = matches[1]; |
|
document.getElementById("userCount").innerHTML = matches[1]; |
|
} else if (matches = ev.data.match(/^pause (.+)$/)) { |
|
video.currentTime = matches[1]; |
|
video.pause(); |
|
} else { |
|
if (iAmControlling()) return; |
|
var estimatedTimeOnMaster = parseInt(ev.data)+1; |
|
if (Math.abs(estimatedTimeOnMaster-video.currentTime)>5) |
|
video.currentTime = estimatedTimeOnMaster; |
|
if (video.paused) video.play(); |
|
} |
|
}; |
|
$_("#takeControl").onclick = function(ev) { |
|
conn.send("control "+$_("#name").value); |
|
}; |
|
$_("#leave").onclick = function() { |
|
conn.close(); |
|
$_("#room").className = "inactive"; |
|
$_("#registration").className = "active"; |
|
}; |
|
}; |
|
}; |
|
|
|
function iAmControlling() { |
|
return $_("#controller").innerHTML == $_("#name").value; |
|
} |
|
|
|
function $_(sel) { |
|
return document.querySelector(sel); |
|
} |
|
</script> |
|
|
|
<div id="registration" class="active"> |
|
<p>Username: <input id="name" /> <button id="join">Join Room</button></p> |
|
</div> |
|
|
|
<div id="room" class="inactive"> |
|
User: <span id="username"></span> |
|
<button id="leave">Leave Room</button> |
|
<p>Users: <span id="userCount"></span></p> |
|
<p>Controller: <span id="controller">---</span> <button id="takeControl">Take Control</button></p> |
|
<p><video src="popeye.mp4" controls></video></p> |
|
</div> |