如何在 Crystal 中创建流式 HTTP 服务器?

How to create a streaming HTTP Server in Crystal?

我想创建一个类似于 Twitter Streaming API 的服务器,以便客户端可以实时读取响应并保持连接。如何在 Crystal 中做到这一点?

摘自此issue:

@MakeNowJust 说:

You should append \n to sent text to gets in client and do io.flush.

require "http/server"

port = 5000

server = HTTP::Server.new(port) do |context|
  loop do
    context.response.puts "Something\n"
    context.response.flush
    sleep 1
  end
end

puts "Listening on #{port}"
server.listen

@rx14 说:

crystal already handles writing chunked responses. Just keep on writing to the output response, and call flush when you want to ensure the client receives the message. If there is no content length header, the response will automatically select chunked encoding for you.