如何从我的sinatra应用程序中的类传递数据到websocket-rack?

我在sinatra应用程序中有一个websocket-rack的工作配置,用于具有多个屏幕的物理安装。 有一些function可以使消息在websockets中来回传递。

我的问题是这样的:我有一个页面带有标准的Web表单(即不是websocket表单),我的目标是从该表单中收集params,将params转换为字符串变量,然后发送该变量的内容(字符串)通过websocket到不同的页面/屏幕。 对于我的生活,我无法弄清楚如何做一个应该是一个相对简单的任务,因为从我的应用程序中的主类,我无法与我的Socket类进行通信,从我理解的基本上是机架应用。

我试图通过将resque设置为中间人来解决它,但很快发现我的问题没有改变。 我无法弄清楚如何从另一个类调用方法和/或将变量传递给Socket,以便它将推送到浏览器。

基本上,我有一个app.rb是这样的:

module SomeThing class App < Sinatra::Base get '/' do #show a form end post '/submit' do #receive params #save params new_message = params.inspect #dream up some way to pass new_message to websocket end post '/otherscreen' do #have an open websocket to receive new_message end end class Socket < Rack::WebSocket::Application def on_open(env) puts "Client connected" send_data "Oh hai!" end def on_close(env) puts "Client disconnected" end def on_message(env, msg) puts "Received message from client: " + msg end def on_error(env, error) puts "An error occured: " + error.message end def pass_message(env, new_message) send_data new_message end end end 

如果您需要更多信息来解决此问题,请与我们联系。 我很乐意提供所需的一切,只是不确定现在可能是什么。

你知道我怎么解决这个问题吗? 这太痛苦了。

提前谢谢!

所以,我写信给websocket-rack的作者Bernard Potocki,他说:

“我通常做的是保存某种类变量的活动连接列表。其中一个可能的实现可能看起来像这个要点: https : //gist.github.com/imanel/a00d6b65561ebba43b9a ”

gist的内容,如果它被删除:

 class Socket < Rack::WebSocket::Application def self.connections @connections ||= [] end def self.send_to_all(message) @connections.each {|connection| connection.send_data(message) end def on_open(env) self.class.connections << self end def on_close(env) self.class.connection.delete(self) end end 

但是,最终,我没有测试此解决方案,因为我们能够使用Redis和Event Machine解决此问题,因此请注意这也是一个选项。