easierbycode
10/27/2011 - 5:44 PM

Simple Chat app

Simple Chat app

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
<!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>