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
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
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
5条答案
按热度按时间eqqqjvef1#
虽未试过,但不宜过猛:
此外,Cramp有一个WebSocket实现,它可以直接与Thin/Rainbows!一起工作,所以你甚至不需要在另一个端口上运行服务器。
pvcm50d12#
谢谢Konstantin...这很有用!我必须稍微调整你的代码。我在我修改的地方添加了注解。
67up9zun3#
我偶然发现了这个websocket-rack github项目,它基本上是一个机架化的em-websocket,实际上它可以很好地与一个Sinatra应用程序并行工作config.ru:
玩得开心点!
柯林
icnyk63a4#
我一直在使用sinatra-websocket,它可以让你在与Sinatra相同的进程和端口上运行WebSocket服务器。
免责声明:我是维护者。
zi8p0yeb5#
仅供参考,您也可以将Padrino应用程序与EventMachine一起使用(因为它们是Sinatra应用程序的子集):