Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

jamtur01 commented Sep 26, 2013

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
You can’t perform that action at this time.