Skip to content

Instantly share code, notes, and snippets.

@dsample
Created January 31, 2014 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsample/8724881 to your computer and use it in GitHub Desktop.
Save dsample/8724881 to your computer and use it in GitHub Desktop.
Simple WebSocket event mirror

This is a simple WebSockets app which demostrates how an event could be sent from one browser to another device's browser.

The code was adapted from Martyn Loughran's em-websocket tutorial article http://rubylearning.com/blog/2010/10/01/an-introduction-to-eventmachine-and-how-to-avoid-callback-spaghetti/ which was published as a Gist https://gist.github.com/mloughran/604404

The idea would be to eventually make it into a snippet which could be launched from a browser bookmarklet to add synchronisation between browsers on all kinds of devices.

<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var incoming = false;
var processEvent = function(event, id, value) {
incoming = true;
obj = document.getElementById(id); //$('#' + id);
switch(event) {
case 'click':
console.log("clicked on another device: #"+ id);
obj[event]();
break;
case 'value':
console.log("data entered on another device: #"+ id + ": " + value);
obj.value = value;
break;
}
incoming = false;
}
var socket = new WebSocket('ws://0.0.0.0:8080/');
socket.onopen = function() {
console.log("Socket opened");
};
socket.onmessage = function(message) {
var info = JSON.parse(message.data);
console.log(info.event, info.id, info.value);
processEvent(info.event, info.id, info.value);
};
socket.onclose = function() {
console.log("Socket closed");
};
sendClick = function(id) {
if (incoming) return;
socket.send('{"event": "click", "id": "' + id + '"}');
}
sendChange = function(id) {
if (incoming) return;
var value = document.getElementById(id).value;
socket.send('{"event": "value", "id": "' + id + '", "value": "' + value + '"}');
}
})
</script>
</head>
<body>
<input id="test_input" onChange="sendChange(this.id)" />
<button id="test_button" onClick="sendClick(this.id)">test</button>
</body>
require 'rubygems'
require 'eventmachine'
require 'em-websocket'
EM.run {
websocket_connections = []
EM::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
ws.onopen {
puts "Websocket connection opened"
websocket_connections << ws
}
ws.onmessage do |msg|
puts "event: " + msg
websocket_connections.each { |socket| socket.send msg unless ws == socket }
end
ws.onclose {
puts "Websocket connection closed"
websocket_connections.delete(ws)
}
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment