1
0
mirror of https://github.com/balkian/SWCM.git synced 2024-11-22 20:52:29 +00:00
SWCM/ServidorConcurrente/servidor.rb

46 lines
1.4 KiB
Ruby
Raw Normal View History

2011-04-24 15:28:40 +00:00
require 'socket'
numCon = 0
maxCon = 10
2011-04-24 15:35:13 +00:00
def respond(socket, code, body) # Genera respuestas
2011-04-24 15:28:40 +00:00
socket.puts "HTTP/1.0 #{ code }"
socket.puts "Content-type: text/html"
socket.puts "Content-length: #{ body.length }"
socket.puts
socket.puts body
socket.close
end
server = TCPServer.open(8080)
puts "web server created at port 8080"
loop do
2011-04-24 15:35:13 +00:00
if(numCon < maxCon) # Si no se ha superado el número máximo de hebras
sock = server.accept # Acepta conexión del cliente
2011-04-24 15:28:40 +00:00
t = Thread.new(sock) do |socket|
2011-04-24 15:35:13 +00:00
numCon=numCon+1
request = socket.gets # Lee la primera línea
o = socket.gets until ( o != "") # cabecera acaba con línea vacía
2011-04-24 15:28:40 +00:00
unless request =~ /^GET/ # Si el comando no esta soportado
respond socket, "400 Bad Request", "<html><body><h1>Comando desconocido</h1></body></html>"
next # Acaba el ciclo
end
request =~ /^GET \/(.*) .*/ # GET /(fichero) HTTP/1.x
path = $1
if path == "" || path =~ /\/$/ then path += "index.html" end # Inserta index.html
if File.exists?(path)
file = open(path) # Lee fichero y prepara respuesta
puts "OK #{ path }"
respond socket, "200 OK", file.read
else
puts "NotFound #{ path }" # Si el fichero no existe
respond socket, "404 Not Found", "<html><body><h1>Recurso no encontrado</h1></body></html>"
end
numCon=numCon-1;
end
end
end