Chinaunix首页 | 论坛 | 博客
  • 博客访问: 383212
  • 博文数量: 69
  • 博客积分: 1984
  • 博客等级: 上尉
  • 技术积分: 953
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-28 00:43
个人简介

学无所长,一事无成

文章分类

全部博文(69)

文章存档

2015年(19)

2014年(14)

2013年(9)

2012年(17)

2010年(10)

我的朋友

分类: Python/Ruby

2012-07-04 14:59:14

参考文章:

 

使用 Ruby Eventmachine 的 Websockets August 20th 2010

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

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

 

设置 EventMachine

使用 for 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.

阅读(3004) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~