Any success with Sinatra working together with EventMachine WebSockets?

前端 未结 5 2247
陌清茗
陌清茗 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:37

    I've been using sinatra-websocket. It let's you run the websocket server in the same process and on the same port as Sinatra.

    Disclaimer: I'm the maintainer.

    require 'sinatra'
    require 'sinatra-websocket'
    
    set :server, 'thin'
    set :sockets, []
    
    get '/' do
      if !request.websocket?
        erb :index
      else
        request.websocket do |ws|
          ws.onopen do
            ws.send("Hello World!")
            settings.sockets << ws
          end
          ws.onmessage do |msg|
            EM.next_tick { settings.sockets.each{|s| s.send(msg) } }
          end
          ws.onclose do
            warn("websocket closed")
            settings.sockets.delete(ws)
          end
        end
      end
    end
    
    __END__
    @@ index
    
      
         

    Simple Echo & Chat Server

提交回复
热议问题