Skip to content

Instantly share code, notes, and snippets.

@fxn
Created June 5, 2011 16:13
Show Gist options
  • Save fxn/1009108 to your computer and use it in GitHub Desktop.
Save fxn/1009108 to your computer and use it in GitHub Desktop.
# encoding: binary
require 'socket'
require 'zlib'
require 'stringio'
PADDING = 256
GZIP = true
CHUNKED = true
def compress(gzip, io, data)
gzip.write(data)
gzip.flush
io.string.force_encoding('binary')
end
def consume_request(c)
while c.readline != "\r\n"
# do nothing
end
c.close_read
end
def write_common_headers(c)
c.write("HTTP/1.1 200 OK\r\n")
c.write("Connection: close\r\n")
c.write("Content-Type: text/html; charset=UTF-8\r\n")
end
def chunked_response(c, gzip, io, chunks)
c.write("Transfer-Encoding: chunked\r\n")
c.write("\r\n")
for chunk in chunks
data = chunk
data += ' ' * (PADDING - data.size) if PADDING && data.size < PADDING
data = compress(gzip, io, data) if GZIP
c.write("#{data.size.to_s(16)}\r\n#{data}\r\n")
if GZIP
io.truncate(0)
io.rewind
end
puts "chunk sent"
sleep(5) unless chunk == chunks.last
end
c.write("0\r\n\r\n")
end
def ordinary_response(c, gzip, io, chunks)
payload = chunks.join('')
payload = compress(gzip, io, payload) if GZIP
c.write("Content-Length: #{payload.bytesize}\r\n")
c.write("\r\n")
if PADDING
c.write(payload[0...PADDING])
puts "sent a few bytes"
sleep(5)
c.write(payload[PADDING..-1])
else
c.write(payload)
end
end
chunks = [<<HTML1, <<HTML2]
<!DOCTYPE html>
<html lang="en">
<head>
<link href="http://localhost:3001/foo.css" media="screen" rel="stylesheet" type="text/css" />
HTML1
</head>
<body>
<p>Hey!</p>
</body>
</html>
HTML2
io = StringIO.new
io.binmode
gzip = Zlib::GzipWriter.new(io)
begin
server = TCPServer.new('0.0.0.0', 3000)
c = server.accept
c.sync = true
consume_request(c)
write_common_headers(c)
c.write("Content-Encoding: gzip\r\n") if GZIP
if CHUNKED
chunked_response(c, gzip, io, chunks)
else
ordinary_response(c, gzip, io, chunks)
end
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