我一直在处理这段代码,由于某种原因,服务器无法打开索引文件,我不明白为什么。我检查了其他人的代码,看起来没有区别。
这是我的代码:
require 'socket'
class Server
def initialize (base, request, server_name, session, charset)
@base = base
@request = request
@charset = charset
@server_name = server_name
@session = session
serve()
end
def serve ()
access_log()
getAddress()
@contentType = getContentType()
@session.print "HTTP/1.1 200 OK\r\nServer: #{@server_name}\r\nContent-Type: #{@contentType}; charset=@{charset}\r\n\r\n"
getFile()
@base = nil
@request = nil
@server_name = nil
@contentType
@session.close
puts "Session Ended\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
@session = nil
end
def access_log ()
log = File.open(@base + "data/access_log.txt", "w")
log.puts "#{Time.now.localtime.strftime("%Y/%m/%d %H:%M:%S")} #{@session.peeraddr[2]}:#{@session.peeraddr[1]} #{@request}" unless log == nil
log.close
log = nil
end
def getAddress ()
@src = @request
@src.gsub!(/GET /, '').gsub!(/ HTTP.*/, '')
@src.strip
@src = @base + "root" + @src
@src.gsub!('/', '\\')
end
def getContentType ()
ext = nil
ext = File.extname(@src)
return "text/html" if ext == ".html" or ext == ".htm"
return "text/plain" if ext == ".txt"
return "text/css" if ext == ".css"
return "image/jpeg" if ext == ".jpeg" or ext == ".jpg"
return "image/gif" if ext == ".gif"
return "image/bmp" if ext == ".bmp"
return "text/plain" if ext == ".rb"
return "text/xml" if ext == ".xml"
return "text/xml" if ext == ".xsl"
#return "image/x-icon" if ext == ".ico" or ext == ".icon"
return "text/html"
end
def getFile ()
begin
if !File.exist?(@src)
puts "File: #{@src} could not be found"
if @contentType.include?("image")
file = File.open(@base + "root/server_files/broken_image.png", "r").each do |code|
@session.puts code
end
else
file = File.open(@base + "root/server_files/error404.html", "r").each do |code|
@session.puts code
end
end
else
puts "File #{@src} was opened"
file = File.open(@src, "r").each do |code|
@session.puts code
end
end
ensure
file.close unless file == nil
end
end
end
base = "C:\\Base\\"
server_name = "Some Server"
host = "localhost"
port = 80
charset = "UFT-8"
server = TCPServer.new(host, port)
puts "~ Server hosted on #{host}:#{port} ~\n====================================\n"
loop {
Thread.new(server.accept) do |session|
request = session.gets
puts "#{session.peeraddr[2]}:#{session.peeraddr[1]} #{request}"
Server.new(base, request, server_name, session, charset)
end
}
p = gets.chomp
server.close