Sinatra与EventMachine WebSockets一起工作是否成功?

时间:2010-06-08 16:46:53

标签: ruby sinatra websocket rack eventmachine

我一直在使用Sinatra,我想通过websockets推送数据,为我的web-app添加一些实时功能。

我已成功使用gem'em-websocket',但无法编写一个带有sinatra Web服务器和Web套接字服务器的ruby文件。

我试过旋转跑!或者开始!在单独的线程中关闭方法但没有成功。

有没有人让这个工作?

我希望将它们放在同一个文件中,然后在两台服务器之间共享变量。

谢谢!

5 个答案:

答案 0 :(得分:27)

没试过,但不应该太难:

require 'em-websocket'
require 'sinatra/base'
require 'thin'

EM.run do
  class App < Sinatra::Base
    # Sinatra code here
  end

  EM::WebSocket.start(:host => '0.0.0.0', :port => 3001) do
    # Websocket code here
  end

  # You could also use Rainbows! instead of Thin.
  # Any EM based Rack handler should do.
  Thin::Server.start App, '0.0.0.0', 3000
end

此外,Cramp有一个websocket实现,可以直接使用Thin / Rainbows!您可能能够解压缩,因此您甚至不需要在另一个端口上运行服务器。

答案 1 :(得分:20)

谢谢康斯坦丁......这很有效!我不得不稍微调整你的代码。我添加了评论,我改变了它。

-poul

require 'rubygems'      # <-- Added this require
require 'em-websocket'
require 'sinatra/base'
require 'thin'

EventMachine.run do     # <-- Changed EM to EventMachine
  class App < Sinatra::Base
      get '/' do
          return "foo"
      end
  end

  EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws| # <-- Added |ws|
      # Websocket code here
      ws.onopen {
          ws.send "connected!!!!"
      }

      ws.onmessage { |msg|
          puts "got message #{msg}"
      }

      ws.onclose   {
          ws.send "WebSocket closed"
      }

  end

  # You could also use Rainbows! instead of Thin.
  # Any EM based Rack handler should do.
  App.run!({:port => 3000})    # <-- Changed this line from Thin.start to App.run!
end

答案 2 :(得分:17)

我偶然发现了这个websocket-rack github项目,该项目基本上是一个机架化的em-websocket,实际上它可以与Sinatra应用程序很好地并行工作。这是我的config.ru:

require 'rubygems'
require 'rack/websocket'
require 'sinatra/base'

class WebSocketApp < Rack::WebSocket::Application
  # ...
end

class SinatraApp < Sinatra::Base
  # ...
end

map '/ws' do
  run WebSocketApp.new
end

map '/' do
  run SinatraApp
end

玩得开心!
科林

答案 3 :(得分:11)

我一直在使用sinatra-websocket。它允许您在与Sinatra相同的进程和相同的端口上运行websocket服务器。

免责声明:我是维护者。

require 'sinatra'
require 'sinatra-websocket'

set :server, 'thin'
set :sockets, []

get '/' do
  if !request.websocket?
    erb :index
  else
    request.websocket do |ws|
      ws.onopen do
        ws.send("Hello World!")
        settings.sockets << ws
      end
      ws.onmessage do |msg|
        EM.next_tick { settings.sockets.each{|s| s.send(msg) } }
      end
      ws.onclose do
        warn("websocket closed")
        settings.sockets.delete(ws)
      end
    end
  end
end

__END__
@@ index
<html>
  <body>
     <h1>Simple Echo & Chat Server</h1>
     <form id="form">
       <input type="text" id="input" value="send a message"></input>
     </form>
     <div id="msgs"></div>
  </body>

  <script type="text/javascript">
    window.onload = function(){
      (function(){
        var show = function(el){
          return function(msg){ el.innerHTML = msg + '<br />' + el.innerHTML; }
        }(document.getElementById('msgs'));

        var ws       = new WebSocket('ws://' + window.location.host + window.location.pathname);
        ws.onopen    = function()  { show('websocket opened'); };
        ws.onclose   = function()  { show('websocket closed'); }
        ws.onmessage = function(m) { show('websocket message: ' +  m.data); };

        var sender = function(f){
          var input     = document.getElementById('input');
          input.onclick = function(){ input.value = "" };
          f.onsubmit    = function(){
            ws.send(input.value);
            input.value = "send a message";
            return false;
          }
        }(document.getElementById('form'));
      })();
    }
  </script>
</html>

答案 4 :(得分:8)

仅供参考,您也可以将Padrino应用与EventMachine一起使用(因为它们是Sinatra应用的子集):

require 'rubygems'
require 'eventmachine'
require 'padrino-core'
require 'thin'
require ::File.dirname(__FILE__) + '/config/boot.rb'

EM.run do
  Thin::Server.start Padrino.application, '0.0.0.0', 3000
end

干杯, 麦克