Skip to content

Instantly share code, notes, and snippets.

@boof
Created March 10, 2010 08:54
Show Gist options
  • Save boof/327694 to your computer and use it in GitHub Desktop.
Save boof/327694 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'mq'
#require 'yajl'
#require 'sequel'
require 'em-websocket'
require 'uuid'
AMQP.start(:host => 'localhost') do
uuid = UUID.new # drop UUID in favour of 1
chat = MQ.new.fanout 'chat'
EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
ws.onopen do
puts "WebSocket opened"
# (1) instead of asking uuid to generate an id, select it from db
mq = MQ.new
mq.queue(uuid.generate).bind(chat).subscribe { |t| ws.send t }
end
ws.onmessage do |msg|
# (1) use json instead of plain text to fetch the id and
# - map the id into the username via db call
# - rebuild the message with username and timestamp
# - only send it to a single user?
chat.publish(msg)
end
ws.onclose do
puts "WebSocket closed"
end
end
end
<!DOCTYPE html>
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'></script>
<script>
$(function() {
if ("WebSocket" in window) {
$("form").submit(function(e) {
e.preventDefault();
var input = $('input[type="text"]', this);
ws.send(input.val());
input.val('');
});
ws = new WebSocket("ws://localhost:8080/");
ws.onmessage = function(e) {
var $p = $('<p>');
$p.html(e.data);
$('#messages').prepend($p);
};
ws.onclose = function() {
$('#messages').prepend("Local: Connection closed...");
};
ws.onopen = function() {
$('#messages').prepend("Local: Connection established...");
};
} else {
$('#messages').html("TODO use http://github.com/gimite/web-socket-js");
}
});
</script>
</head>
<body>
<form>
<input type="text"/>
<input type="submit"/>
</form>
<div id="messages">
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment