-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
HTTP Server with chunked transfer encoding #5004
Comments
You should append require "http/server"
port = 5000
server = HTTP::Server.new(port) do |context|
puts "Got request"
# `context.response.headers["Transfer-Encoding"] = "chunked"` is default.
loop do
puts "Writing"
context.response.puts "Query: #{context.request.query}"
context.response.flush
sleep 5
end
end
puts "Listening on #{port}"
server.listen |
@vladfaust if @makenowjust didn't make that crystal clear: 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. |
@RX14 Thank you for detailed explanation! |
@RX14 @makenowjust thank you guys. Should I create a separate issue stating that we need more docs for that? @RX14 Your quote could be used. |
Regarding docs: no. I prefer to use StackOverflow, it's a living "missing docs and examples". It's simply impossible to put every use case in documentation. So this should be really asked in StackOverflow. |
Also I'm thinking that I don't know much about IO. |
I want to implement Twitter-like functionality of continuously streaming data without closing the connection. Websockets don't work for me for this particular situation.
Twitter server
Twitter Streaming API client shard currently has this implementation (simplified) of streaming tweets:
And an application may do this:
It has following headers:
RESPONSE HEADERS: HTTP::Headers{"connection" => "close", "content-Encoding" => "gzip", "content-type" => "application/json", "date" => "...", "server" => "tsa", "transfer-encoding" => "chunked", "x-connection-hash" => "..."}
and it actually continuously gets the response! Each time a new tweet is posted, this block is yielded, the connection stays alive forever!Yes, that's true, I already have Telegram bot posting new tweets in a channel.
Implementing the same functionality
After some googling I've found that Twitter might use Chunked transfer encoding.
As I can see in the CHANGELOG:
But HTTP::Server::Response::Output#unbuffered_write is private. 🤔
Therefore, I clearly don't get how to serve chunked responses.
My trials
So far, this is what I've tried to do:
server.cr
client.cr
Output
This is server output:
And this is what I got on the client. Note that the output is empty until I press Ctrl-C on server:
Please help me implementing a chunked server in Crystal!
The text was updated successfully, but these errors were encountered: