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

问题描述:

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

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.

我已经成功地单独使用了 gem 'em-websocket',但无法编写一个具有 sinatra 网络服务器和网络套接字服务器的 ruby​​ 文件.

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.

有人用过这个吗?

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

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

谢谢!

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

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

此外,Cramp 有一个 websocket 实现,可以直接与 Thin/Rainbows 配合使用!您可能能够提取,因此您甚至不需要在另一个端口上运行服务器.

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.