Created
September 26, 2013 17:27
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ruby -rwebrick -e'WEBrick::HTTPServer.new(:Port => 3000, :DocumentRoot => Dir.pwd).start'
:)