Skip to content

Instantly share code, notes, and snippets.

@tgittos
Created June 15, 2015 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgittos/56f3d65c8ab161591241 to your computer and use it in GitHub Desktop.
Save tgittos/56f3d65c8ab161591241 to your computer and use it in GitHub Desktop.
Basic C-style web server in Ruby
#! /usr/bin/env ruby
require 'socket'
include Socket::Constants
PORT = 8888
HOST = '0.0.0.0'
socket = Socket.new(AF_INET, SOCK_STREAM, 0)
address = Socket.pack_sockaddr_in(PORT, HOST)
socket.bind(address)
socket.listen(5)
puts "Server listening on port #{PORT}..."
loop do
client, address_info = socket.accept
#request = client.recvfrom(1024)[0]
request = client.gets
STDERR.puts request
verb, resource = request.split(' ')
response = resource
headers = <<-RESP
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: #{response.bytesize}
Connection: close
RESP
client.print headers
client.print "\r\n"
client.print response
client.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment