gpt4 book ai didi

ruby - padrino && websockets

转载 作者:数据小太阳 更新时间:2023-10-29 07:54:04 25 4
gpt4 key购买 nike

我正在寻找一种在 Padrino 中打开和使用 websockets 的方法应用。我知道 Padrino 使用单线程,但我正在寻找一种方法来打开 websocket 并在其“onopen”、“onclose”、“onmessage”方法和 Padrino Controller 之间共享变量。

知道它是如何完成的吗?

我调查过的链接:

Examples of Eventmachine usage with Padrino and Sinatra (只有 Sinatra 为我工作) em-websocket on GitHub

更新 1:这是我的 main.rb:

    require 'rubygems'      # <-- Added this require
require 'em-websocket'
require 'padrino-core'
require 'thin'

require File.expand_path("../config/boot.rb", __FILE__)

SOCKETS = []
EventMachine.run do # <-- Changed EM to EventMachine
# class App < Sinatra::Base
# get '/' do
# SOCKETS.each {|s| s.send "fooooo"}
# 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!!!!"
SOCKETS << ws
}

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

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

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!
Thin::Server.start Padrino.application, '0.0.0.0', 3000

结束

我遇到了这个异常:

/home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/daemonizing.rb:2:in `require': no such file to load -- daemons (LoadError)
from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/daemonizing.rb:2:in `<top (required)>'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/server.rb:50:in `<class:Server>'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/server.rb:48:in `<module:Thin>'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/server.rb:1:in `<top (required)>'
from main.rb:39:in `block in <main>'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `call'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run_machine'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run'
from main.rb:9:in `<main>'

更新 2:解决感谢内森!我刚刚将“守护进程”添加到 Gemfile 并重新加载了我的应用程序。

最佳答案

也许你需要安装守护进程:

编辑你的 Gemfile:

# Adding this
gem 'daemons'

安装缺少的 gem:

$ bundle install

关于ruby - padrino && websockets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7497441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com