Skip to content

Instantly share code, notes, and snippets.

@FooBarWidget
Created June 5, 2011 13:04
Show Gist options
  • Save FooBarWidget/1008944 to your computer and use it in GitHub Desktop.
Save FooBarWidget/1008944 to your computer and use it in GitHub Desktop.
# encoding: binary
require 'socket'
require 'zlib'
require 'stringio'
GZIP = true
CHUNKED = true
$io = StringIO.new
$io.binmode
$gzip = Zlib::GzipWriter.new($io)
$uncompressed_written = 0
$compressed_written = 0
def write_socket(sock, data)
if GZIP
$gzip.write(data)
$gzip.flush
str = $io.string.force_encoding('binary')
else
str = data.force_encoding('binary')
end
$uncompressed_written += data.size
$compressed_written += str.size
sock.write("#{str.size.to_s(16)}\r\n#{str}\r\n")
$io.truncate(0)
$io.rewind
puts "Written u=#{$uncompressed_written} / c=#{$compressed_written} bytes, press Enter to continue"
STDIN.readline
end
begin
server = TCPServer.new('0.0.0.0', 3000)
c = server.accept
c.sync = true
while c.readline != "\r\n"
# Do nothing
end
c.close_read
c.write("HTTP/1.1 200 OK\r\n")
c.write("Connection: close\r\n")
if CHUNKED
c.write("Transfer-Encoding: chunked\r\n")
end
if GZIP
c.write("Content-Encoding: gzip\r\n")
end
c.write("Content-Type: text/html; charset=iso-8859-1\r\n")
c.write("\r\n")
write_socket(c, '<link rel="stylesheet" type="text/css" href="/foo.css">')
20.times do |i|
data = "#{'x' * 100} #{i}<br>\n"
write_socket(c, data)
end
c.write("0\r\n\r\n")
c.close_write
ensure
$gzip.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment