参考文章:

http://jxs.me/2010/08/20/websockets-using-ruby-eventmachine/

使用 Ruby Eventmachine 的 Websockets August 20th 2010

HTML5增加了很多新特性,使开发更便利,最终使用更舒心。这里我们讨论其中一个新特性:WebSockets。我们会基于 Ruby 的 Eventmachine gem 来实现。

首先确保你的浏览器支持 WebSockets (如 Chrome, Safari, Firefox trunk)。

设置 EventMachine

使用 EventMachine for WebSockets 非常简单,有个现成的  em-websockets gem。 启动 EventMachine.run block 就可以了, EventMachine::WebSocket.start 会干剩下的活。 It provides a socket object that resembles the javascript WebSocket spec with callbacks for onopen, onmessage, and onclose.

  1. require 'eventmachine'
  2. require 'em-websocket'

  3. @sockets = []
  4. EventMachine.run do
  5.   EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |socket|
  6.     socket.onopen do
  7.       @sockets << socket
  8.     end
  9.     socket.onmessage do |mess|
  10.       @sockets.each {|s| s.send mess}
  11.     end
  12.     socket.onclose do
  13.       @sockets.delete socket
  14.     end
  15.   end
  16. end

本例子中, connected sockets 被添加到数组中,并在 onmessage 被触发时进行广播。

客户端

The client side script listens for keypresses and sends them to the websocket. On receiving a message, which is just a single letter in this case, the corresponding letter will be lit up.

  1. var socket;
  2. var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  3. function animateCharacter(letter)
  4. {
  5.   var upper = letter.toUpperCase();
  6.   $('#character_' + upper)
  7.     .stop(true,true)
  8.     .animate({ opacity: 1}, 100)
  9.     .animate({ opacity: .2}, 100);
  10. }

  11. function setup()
  12. {
  13.   var target = $('#alphabet');
  14.   for(var i = 0; i <=alphabet.length; i++)
  15.   {
  16.     var char = alphabet.charAt(i);
  17.     target.append(' + char +'">' + char + ');
  18.   }
  19.   connect();

  20.   $(document).keypress(function(e){
  21.     var char = String.fromCharCode(e.keyCode);
  22.     socket.send(char);
  23.   });
  24. };

  25. function connect(){
  26.   socket = new WebSocket('ws://h.jxs.me:8080');
  27.   socket.onmessage = function(mess) {
  28.     animateCharacter(mess.data);
  29.   };

  30. };

  31. window.onload += setup();

With it all put together, WebSockets makes for a simple way to connect users together through the browser without plugins, polling, or other ugly frameworks.

12-25 21:31