来自“Sinatra:正在运行”的流式示例不起作用

时间:2012-08-13 09:40:16

标签: sinatra

我试图从 Sinatra:Up and Running 一书中运行这个例子。 46,但无法让它发挥作用。这是程序代码:

require 'sinatra'

before do
  content_type :txt
end

connections = []

get '/consume' do
  stream(:keep_open) do |out|
    # store connection for later on
    connections << out
    # remove connection when closed properly
    out.callback { connections.delete(out) }
    # remove connection when closed due to an error
    out.errback do
      logger.warn 'we just lost a connection!'
      connections.delete(out)
    end
  end
end

get '/broadcast/:message' do
  connections.each do |out| 
    out << "#{Time.now} -> #{params[:message]}" << "\n"
  end
  "Sent #{params[:message]} to all clients."
end

测试代码的说明如下:

It’s a little tricky to demonstrate the behavior in text, but a good demonstration would
be to start the application, then open a web browser and navigate to http://localhost:
4567/consume. Next, open a terminal and use cURL to send messages to the server.
    $ curl http://localhost:4567/broadcast/hello
    Sent hello to all clients.
If you look back at the web browser, you should see that the content of the page has
been updated with a time stamp and the message that you sent via the terminal. The
connection remains open, and the client continues to wait for further information from
the server.

当我按照这些说明操作时,我没有收到任何错误,但是“hello”消息没有出现在浏览器中。我和Webrick一起经营着Sinatra。为什么不起作用?

谢谢!

更新(康斯坦丁的薄弱建议)

我现在开始瘦身并执行本书和OP中描述的两个步骤。您可以看到thin确实收到了这两个请求。但是,我仍然没有在浏览器中看到输出“hello”。

>rackup
>> Thin web server (v1.4.1 codename Chromeo)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:9292, CTRL+C to stop
127.0.0.1 - - [13/Aug/2012 12:48:03] "GET /consume HTTP/1.1" 200 - 0.0900
127.0.0.1 - - [13/Aug/2012 12:48:03] "GET /favicon.ico HTTP/1.1" 404 447 0.0000
127.0.0.1 - - [13/Aug/2012 12:49:02] "GET /broadcast/hello HTTP/1.1" 200 26 0.00
00
127.0.0.1 - - [13/Aug/2012 12:57:00] "GET /consume HTTP/1.1" 200 - 0.0000

也许错误发生在我的configu.ru文件中:

require './streaming.rb'

run Sinatra::Application

3 个答案:

答案 0 :(得分:1)

在Thin上运行Sinatra。 Webrick不支持:keep_open。确保您运行的是Sinatra 1.3.3或更高版本。

答案 1 :(得分:1)

我遇到了同样的问题。为了加快响应速度,我使用了

before do
  content_type 'text/event-stream'
end

答案 2 :(得分:0)

第二条路线必须是POST:

post '/broadcast/:message' do
  connections.each do |out|
    out << "#{Time.now} -> #{params[:message]}" << "\n"
  end

  "Sent #{params[:message]} to all clients."
end

之后,您还必须将消息发送到服务器:

curl -vX POST 127.0.0.1:4567/broadcast/hello