参考文章:
使用 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.
- require 'eventmachine'
- require 'em-websocket'
- @sockets = []
- EventMachine.run do
- EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |socket|
- socket.onopen do
- @sockets << socket
- end
- socket.onmessage do |mess|
- @sockets.each {|s| s.send mess}
- end
- socket.onclose do
- @sockets.delete socket
- end
- end
- 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.
- var socket;
- var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- function animateCharacter(letter)
- {
- var upper = letter.toUpperCase();
- $('#character_' + upper)
- .stop(true,true)
- .animate({ opacity: 1}, 100)
- .animate({ opacity: .2}, 100);
- }
- function setup()
- {
- var target = $('#alphabet');
- for(var i = 0; i <=alphabet.length; i++)
- {
- var char = alphabet.charAt(i);
- target.append('+ char +'">' + char + ');
- }
- connect();
- $(document).keypress(function(e){
- var char = String.fromCharCode(e.keyCode);
- socket.send(char);
- });
- };
- function connect(){
- socket = new WebSocket('ws://h.jxs.me:8080');
- socket.onmessage = function(mess) {
- animateCharacter(mess.data);
- };
- };
- 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.
阅读(3059) | 评论(0) | 转发(0) |