return a binary response from a http server in ruby

To return a binary response from an HTTP server in Ruby, you need to set the response's content type to "application/octet-stream". Then, you can set the response body to the binary data using the "write" method of the response object.

Here's an example code snippet that demonstrates how to do this:

main.rb
require 'socket'

server = TCPServer.new('localhost', 8080)

loop do
  client = server.accept

  # read the request
  request_line = client.gets
  puts request_line

  # send the response
  client.puts "HTTP/1.1 200 OK"
  client.puts "Content-Type: application/octet-stream"
  client.puts "Content-Disposition: attachment; filename=myfile.bin"
  client.puts

  # binary data to be sent
  binary_data = [0x00, 0xFF, 0x55, 0xAA].pack("C*")

  # write the binary data to the response
  client.write(binary_data)

  client.close
end
529 chars
26 lines

In this example, the server listens for incoming connections on port 8080 of the localhost. When a request is received, it sends a response with a content type of "application/octet-stream" and a content disposition of "attachment", which tells the browser to treat the response as a file download. Then, it writes the binary data to the response using the "write" method of the client object. Finally, it closes the connection.

gistlibby LogSnag