Skip to content

Instantly share code, notes, and snippets.

@rociiu
Forked from JoeyButler/chat.html
Created October 28, 2011 10:08
Show Gist options
  • Save rociiu/1322014 to your computer and use it in GitHub Desktop.
Save rociiu/1322014 to your computer and use it in GitHub Desktop.
Simple Chat app
<!DOCTYPE html>
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js'></script>
<script>
$(document).ready(function(){
function debug(str){ $("#debug").append("<p>"+str+"</p>"); };
if(typeof WebSocket === 'undefined') {
alert("Your browser does not support websockets.")
}
ws = new WebSocket("ws://0.0.0.0:8100");
ws.onmessage = function(evt) { $("#msg").append("<p>"+evt.data+"</p>"); };
ws.onclose = function() { debug("socket closed"); };
ws.onopen = function() {
debug("connected...");
ws.send("hello server");
};
var keyboard = $("#keyboard");
keyboard.keyup(function (event) {
// The enter key.
if(event.keyCode == 13) {
ws.send(keyboard.val());
keyboard.val('');
}
});
});
</script>
</head>
<body>
<div id="debug"></div>
<div id="msg"></div>
<textarea id="keyboard"></textarea>
</body>
</html>
require 'rubygems'
require 'eventmachine'
require 'em-websocket'
EM.run do
@main_channel = EM::Channel.new
@subscribers = []
EM::WebSocket.start(:host => "0.0.0.0", :port => 8100) do |ws|
ws.onopen do
puts "WebSocket connection open"
subscriber_id = @main_channel.subscribe do |msg|
ws.send(msg)
end
ws.send "Welcome!"
ws.onclose do
puts "Connection closed"
@main_channel.unsubscribe(subscriber_id)
end
ws.onmessage do |msg|
@main_channel.push(msg)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment