Search code examples
httpchunked-encodingcrystal-lang

How to create a streaming HTTP Server in Crystal?


I want to create a server similar to Twitter Streaming API, so a client could read the response in real-time staying connected. How to do that in Crystal?


Solution

  • Extracted from this issue:

    @MakeNowJust says:

    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 says:

    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.