Skip to content

Instantly share code, notes, and snippets.

@adelcambre
Created September 26, 2013 17:27
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adelcambre/6717561 to your computer and use it in GitHub Desktop.
Save adelcambre/6717561 to your computer and use it in GitHub Desktop.
A small bit of code to demonstrate the Sockets API in Ruby via a very tiny, very bad, web server.
require 'socket'
NOT_FOUND = "HTTP/1.1 404 Not Found\nContent-Length: 9\n\nNot Found"
OK = "HTTP/1.1 200 OK\n"
socket = Socket.new(:INET, :STREAM)
sockaddr = Socket.sockaddr_in(11080, '127.0.0.1')
socket.bind(sockaddr)
socket.listen(5)
while client_socket = socket.accept[0]
path = client_socket.readline.split[1]
filename = File.expand_path("../#{path}", __FILE__)
if File.file?(filename)
contents = File.read(filename)
client_socket.write(OK)
client_socket.write("Content-Length: #{contents.size}\n\n")
client_socket.write("#{contents}")
else
client_socket.write(NOT_FOUND)
end
client_socket.close
end
@jamtur01
Copy link

ruby -rwebrick -e'WEBrick::HTTPServer.new(:Port => 3000, :DocumentRoot => Dir.pwd).start'

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment