WebSockets Echo EM

This is another implementation of the echo example with out custom ech server. We create an echo server with the EM-Websocket gem that allows easy creation of asynchornous ruby websockets servers based on the ruby event machine.

The client is the same as the WebsocketsEcho example.

Gemfile
source "http://rubygems.org"

gem "haml"
gem 'em-websocket'
Terminal
ruby server.rb

websocketsEchoEM/server.rb
require 'em-websocket'

EventMachine.run {

    EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
        ws.onopen {
          puts "WebSocket connection open"

          # publish message to the client
          ws.send "Hello Client"
        }

        ws.onclose { puts "Connection closed" }
        ws.onmessage { |msg|
          puts "Recieved message: #{msg}"
          ws.send "Pong: #{msg}"
        }
    end
}
websocketsEchoEM/index.html.haml
!!! 5
%html
  %head
    %meta(charset="utf-8")
    %meta(content="IE=edge,chrome=1" http-equiv="X-UA-Compatible")
    %meta(name="viewport" content="width=device-width, initial-scale=1")  
    %link(rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css")
    %script(type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js")
    %script(type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js")
    %title
      WebSockets Echo with EM-WebSockets
  %body
    :javascript
      var WebSocket = window.WebSocket || window.MozWebSocket;

      $(function() {
        var socket = new WebSocket('ws://localhost:8080');

        
        $('#wsSend').click(function() {
          socket.send( $('#wsMessage').val() );
        })  
        socket.onopen = function(event) { 
          $('#console').append('<p>CONNECTED</p>');
        };
        socket.onmessage = function(event) {
          $('#console').append('<p>' + event.data + '</p>');
        }
        socket.onerror = function(event) {
          $('#console').append('<p>ERROR: ' + event.data + '</p>');
        }
      });
      
    %div(data-role="page")
      %input#wsMessage(type='text')
      %a#wsSend(data-role = 'button')
        Send
      #console