1

我正在尝试从《Sinatra: Up and Running p》一书中运行这个示例。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.

当我按照这些说明进行操作时,我没有收到任何错误,但浏览器中没有出现消息“你好”。我正在使用 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
4

3 回答 3

1

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

于 2012-08-13T13:19:11.333 回答
1

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

before do
  content_type 'text/event-stream'
end
于 2012-08-28T20:17:53.290 回答
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
于 2014-12-20T12:32:38.883 回答