Sinatra 与 EventMachine WebSockets 合作是否成功?

发布于 2024-09-04 08:16:21 字数 255 浏览 1 评论 0原文

我已经使用 Sinatra 一段时间了,我想通过 websockets 推送数据来向我的网络应用程序添加一些实时功能。

我已经成功地单独使用了 gem 'em-websocket',但无法编写一个包含 sinatra Web 服务器和 Web-socket 服务器的 ruby​​ 文件。

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

有人让它发挥作用吗?

我希望将它们放在同一个文件中,这样我就可以在两台服务器之间共享变量。

I have been using Sinatra for sometime now and I would like to add some realtime features to my web-app by pushing the data via websockets.

I have successfully used the gem 'em-websocket' on its own, but have not been able to write one ruby file that has a sinatra web server AND a web-socket server.

I've tried spinning the run! or start! methods off in separate threads with no success.

Has anyone gotten this to work?

I want to have them in the same file as I can then share variables between the two servers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

冷默言语 2024-09-11 08:16:21

没有尝试过,但应该不会太难:

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 实现,可以直接使用细/彩虹!您也许能够解压,因此您甚至不需要在另一个端口上运行服务器。

Did not try it, but should not be too hard:

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

Also, Cramp has a websocket implementation that works directly with Thin/Rainbows! you might be able to extract, so you won't even need to run the server on another port.

小矜持 2024-09-11 08:16:21

谢谢康斯坦丁...这有效!我不得不稍微调整一下你的代码。我在修改的地方添加了评论。

-波尔

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

Thanks Konstantin... that worked! I had to tweak your code slightly. I added comments where I changed it.

-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
ι不睡觉的鱼゛ 2024-09-11 08:16:21

我偶然发现了这个 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

玩得开心!
科林

I stumbled onto this websocket-rack github project which is basically a rackified em-websocket and actually got it to work nicely side-by-side with a Sinatra app. Here's my 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

Have fun!
Colin

筱武穆 2024-09-11 08:16:21

我一直在使用 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>

I've been using sinatra-websocket. It let's you run the websocket server in the same process and on the same port as Sinatra.

Disclaimer: I'm the maintainer.

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>
后eg是否自 2024-09-11 08:16:21

仅供参考,您还可以将 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

FYI, you can also use Padrino apps with EventMachine (as they are subsets of Sinatra apps):

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文