Created
November 23, 2012 19:29
-
-
Save shtirlic/4136962 to your computer and use it in GitHub Desktop.
working http server sample
This file contains hidden or 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' | |
require "http/parser" | |
READ_CHUNK = 1024 * 4 | |
socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM) | |
addr = Socket.pack_sockaddr_in(9799, '127.0.0.1') | |
socket.bind(addr) | |
socket.listen(Socket::SOMAXCONN) | |
socket.setsockopt(:SOCKET, :REUSEADDR, true) | |
puts "Server is listening on port = 9799" | |
loop do | |
connection, addr_info = socket.accept | |
parser = Http::Parser.new | |
begin | |
data = connection.readpartial(READ_CHUNK) | |
puts "Buffer = #{data}" | |
parser << data | |
end until parser.headers | |
connection.write("HTTP/1.1 200 \r\n") | |
connection.write("Content-Type: text/html\r\n") | |
connection.write("Status 200 \r\n") | |
connection.write("Connection: close \r\n") | |
connection.write("\r\n\r\n") | |
connection.write("Hello World \r\n") | |
connection.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment