Last active
December 20, 2015 00:49
-
-
Save simlegate/6044634 to your computer and use it in GitHub Desktop.
Ruby 构建一个简单的支持多线程的 Web 服务器
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 'thread' | |
| require 'socket' | |
| class RequestHandler | |
| def initialize(session) | |
| @session = session | |
| end | |
| def process | |
| while @session.gets.chop.length != 0 | |
| end | |
| @session.puts "HTTP/1.1 200 OK" | |
| @session.puts "content-type: text/html" | |
| @session.puts "" # End of headers | |
| @session.puts "<html>" | |
| @session.puts " <body>" | |
| @session.puts " <center>" | |
| @session.puts " <b>#{Time.now}</b>" | |
| @session.puts " <center>" | |
| @session.puts " </body>" | |
| @session.puts "</html>" | |
| @session.close | |
| end | |
| end | |
| server = TCPServer.new("0.0.0.0", "8888") | |
| $currentRequests = [] | |
| $requestedToShutDown = false | |
| while !$requestedToShutDown | |
| session = server.accept | |
| thread = Thread.new(session) do |newSession| | |
| RequestHandler.new(newSession).process | |
| end | |
| $currentRequests.push(thread) | |
| end | |
| $currentRequests.each { |t| Thread.join(t) } | |
| # | |
| # use +curl+ send http requests on Linux or MacOS | |
| # | |
| # curl 0.0.0.0:8888 | |
| # | |
| # result messages: | |
| # | |
| # <html> | |
| # <body> | |
| # <center> | |
| # <b>2013-07-20 18:45:01 +0800</b> | |
| # <center> | |
| # </body> | |
| # </html> | |
| # |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment