INCLUDE_DATA

 
»
S
I
D
E
B
A
R
«
aquisto cialis levitra svizzera tadalafil bestellen viagra prix acheter du viagra acquista levitra cialis sur internet citrate de sildenafil compro viagra levitra ricetta kamagra pharmaceuticals cialis vente libre cialis suisse levitra italia vente de cialis viagra suisse kamagra gel viagra quanto costa cialis 20 mg prix cialis 10mg viagra verkauf cialis moins cher viagra prezzo levitra kopen acheter tadalafil acheter kamagra tadalafil generico impuissance sexuelle cialis preco levitra donna viagra 100 mg comprar cialis generico comprar levitra cialis a vendre procurer du cialis generische cialis vardenafil generico vardenafil generika levitra sur internet generische viagra acheter cialis generique acquista viagra achat cialis viagra 100 mg cialis generico kamagra en france viagra ordonnance acheter viagra achat vardenafil pastilla levitra viagra cialis differenze impotenza sessuale venta viagra medicament cialis curare impotenza kamagra te koop achat cialis 20mg levitra pharmacie cialis receta acquisto viagra net cialis en ligne achat de viagra cialis generique acheter acheter du cialis cialis 20 mg vardenafil 10 mg viagra alternativo citrate de sildenafil cialis sin receta viagra kopen acheter cialis en pharmacie kamagra bestellen comprar viagra pela internet viagra prescrizione levitra donne vente cialis venta de sildenafil achete levitra acheter cialis france venta de levitra viagra kosten cialis marche pas comprar vardenafil disfunzione erettile rimedi vardenafil generique viagra recensioni cialis generico prezzo viagra versand cialis europe viagra venta libre impotenza rimedi cialis rezeptfrei acheter kamagra france levitra ohne rezept acquisto viagra in contrassegno prix de cialis cialis prescrizione viagra acquisto online achat viagra pildoras cialis kamagra generique cialis prezzo cialis inde cialis sur le net acheter cialis en espagne levitra ordonnance viagra naturel cialis 10 mg acquistare levitra procurer du viagra acquisto viagra senza ricetta viagra controindicazioni levitra 20 mg compra viagra impuissance erection acheter cialis pharmacie prezzi levitra viagra ohne rezept kamagra apcalis comprar viagra commander du cialis cialis ricetta medica sildenafil 50 mg sildenafil venta viagra italia pilule levitra sildenafil generico viagra prijs
Creating a HTTP Web Server using Ruby
Feb 20th, 2009 by Jason

I Listen, I Promise

Recently, I recieved a comment on one of my previous posts, Creating a Socket Server and Client in Ruby, that asked about the next step towards taking the simple example to make a working web server. Well, you’ve been heard and I have written up code to do just that. It handles retrieval and sending of headers, handling GET requests, and responding with status.

Request and Response

class RequestInfo
	attr_accessor :headers, :method, :resource
	def initialize
		@headers = {}
	end
end
class ResponseInfo
	attr_accessor :status, :headers, :body
	def initialize
		@headers = {}
		@body = String.new
	end
end

These classes are short and are designed simply to contain the information coming in and going out of the webserver. RequestInfo’s method is used to obtain the method of the request (GET, etc..). Resource is the requested file from the connecting client. Finally, headers is a map of key value pairs corresponding with headers.

ResponseInfo consists of status, which is the first line returned containing 200 OK or 404 Not Found; body,  the content of what’s actually responded with; and headers, the map of headers of the response.

Populate the Request

	request = RequestInfo.new
	response = ResponseInfo.new
	while((current = s.readline).chomp! != "")
		if current[0,3] == "GET"
			methodline = current.split
			request.method = methodline[0]
			request.resource = methodline[1]
		elsif current.match ':'
			headerline = current.split ':',2
			request.headers[headerline[0]] = headerline[1]
		end
	end

This segment handles populating the RequestInfo object, by going through the sent request line by line from the TCPSocket connection s. It retrieves method, resources, and headers in a single while loop.  The headers are retrieved by splitting on the first colon in each line that contains one.

Populate the Respone

	begin
		File.open("public/#{request.resource}","r") do |file|
			while(curline = file.gets)
				response.body << curline
			end
		end
		response.status = "HTTP/1.0 200 OK"
		response.headers["Content-Type"] = "text/html"
		response.headers["Content-Length"] = response.body.length.to_s
	rescue => err
		puts err
		response.status = "HTTP/1.0 404 Not Found"
		response.headers["Content-Type"] = "text/html"
		response.headers["Content-Length"] = "0"
		response.body = ""
	end

Within this segment, we read in a file (looking in a folder called public so the webserver.rb itself cannot be retrieved through a request), appending its contents to the response.body. Afterwards, if all is successful, we respond with a 200 OK along with some other headers like Content-Type and Content-Length. Typically, if there’s an issue it’s because the file cannot be found, so returning a 404 is appropriate.

Note: A suggestion for improving this example is reading the MIME type of the read file so the Content-Type is not hardcoded.

Write Back the Response

	s.write response.status + &quot;\n&quot;
	response.headers.each {|key,value| s.write &quot;#{key}:#{value}\n&quot;}
	s.write &quot;\n&quot; + response.body
	s.close

This writes to the socket connection s, in order, ResponseInfo’s status, headers, and body. Finally, the connection is closed.

All Together Now

class RequestInfo
	attr_accessor :headers, :method, :resource
	def initialize
		@headers = {}
	end
end
class ResponseInfo
	attr_accessor :status, :headers, :body
	def initialize
		@headers = {}
		@body = String.new
	end
end
require "socket"

serv = TCPServer.new('jstaten.com',7881)
loop do
	Thread.start(serv.accept) do |s|
	request = RequestInfo.new
	response = ResponseInfo.new
	while((current = s.readline).chomp! != "")
		if current[0,3] == "GET"
			methodline = current.split
			request.method = methodline[0]
			request.resource = methodline[1]
		elsif current.match ':'
			headerline = current.split ':',2
			request.headers[headerline[0]] = headerline[1]
		end
	end
	if (request.resource == "/")
		request.resource = "index.html"
	end
	begin
		File.open("public/#{request.resource}","r") do |file|
			while(curline = file.gets)
				response.body << curline
			end
		end
		response.status = "HTTP/1.0 200 OK"
		response.headers["Content-Type"] = "text/html"
		response.headers["Content-Length"] = response.body.length.to_s
	rescue => err
		puts err
		response.status = "HTTP/1.0 404 Not Found"
		response.headers["Content-Type"] = "text/html"
		response.headers["Content-Length"] = "0"
		response.body = ""
	end
	s.write response.status + "\n"
	response.headers.each {|key,value| s.write "#{key}:#{value}\n"}
	s.write "\n" + response.body
	s.close
	end
end
end

When the steps are all implemented, you have a working ruby web server. Surely there are improvements to be made upon this creation, but it’s an effective proof-of-concept that can be built off.

I appreciate the feedback from all visitors to my blog, and if you feel that you have any questions or suggestions, feel free to comment away.

Note: Made a few corrections suggested. Thanks!

Creating a Socket Server and Client in Ruby
Jan 8th, 2009 by Jason

Over break, I’ve been experimenting with Ruby a little bit. It’s rather different from the C#/Java syntaxes I’ve leared through schooling. However, I’ve enjoyed using it. And for the reference of myself and others, I’m slapping up a how-to for creating a simple socket server and client.

The Server

require "socket"
serv = TCPServer.new('localhost',7885)
count = 0
loop do
Thread.start(serv.accept) do |s|
count += 1
s.write "You are visitor #{count} to my TCP Ruby Server"
s.close
puts "New visitor: #{count}"
end
end

The server begins by getting the socket library that already comes with Ruby. It then creates an instance of TCPServer, binding it to localhost on port 7885. Count is used to keep track of the number of incoming connections the server receives.

Enter the loop, a new thread will be started upon the blocking method serv.accept and during the life of the thread, it will increment the count, send a message to the visitor, close the connection, and finally write the user count to the console.

The Client


require "socket"
client = TCPSocket.new("localhost",7885)
str = ""
while (add = client.recv(100)) != ""
str += add
end
puts str
client.close

The client simply receives all output sent to it.  It opens a connection with localhost on port 7885. After connecting, it recieves a buffer of 100 bytes until no more are read. The buffer is appended to the final output string, and the connection is closed.

And there you have it, a simple Ruby socket connection. From here you can create such things as a web server, or writing your own protocol. Enjoy!

»  Substance: WordPress   »  Style: Ahren Ahimsa Blog Flux Local - Utah
© Jason Staten 2009