Any success with Sinatra working together with EventMachine WebSockets?

前端 未结 5 2243
陌清茗
陌清茗 2020-12-07 10:02

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

5条回答
  •  鱼传尺愫
    2020-12-07 10:45

    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
    

提交回复
热议问题