Last active
July 26, 2017 12:00
-
-
Save z0rk1i/ba826dcd6a9f80b51ed83ed1b8cb7c11 to your computer and use it in GitHub Desktop.
Time server
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
| # prerequisites: gem install tzinfo | |
| # run: ruby my_time_server.rb | |
| # visit site: http://localhost:2626 | |
| # stress test: siege -c100 'http://localhost:2626/time?Moscow,New%20York' -b -t10s | |
| require 'socket' | |
| require 'tzinfo' | |
| class Server | |
| def initialize(ip, port) | |
| @server = TCPServer.open(port) | |
| print '*'*33+"server started on #{ip}:#{port}"+'*'*33 | |
| @connections = {} | |
| end | |
| @@headers= [ | |
| "HTTP/1.1 200", | |
| "Content-Type: text/html", | |
| "\r\n" | |
| ].join("\r\n") | |
| def prepare_city(city) | |
| city.sub!(/.+\?/, '') | |
| city.sub!('%20', '_') | |
| TZInfo::Timezone.all_identifiers.find { |e| /#{city}/=~ e } | |
| end | |
| def get_local_time_for(city) | |
| tz = TZInfo::Timezone.get city | |
| tz.utc_to_local(Time.now).strftime("%Y-%m-%d %H:%M:%S") | |
| end | |
| def get_cities(client) | |
| cities = [] | |
| raw = client.gets.split(' ').at 1 | |
| raw.gsub!('/', '').split(',').each { |city| cities << prepare_city(city) } | |
| cities | |
| end | |
| def massage(client) | |
| cities = get_cities client | |
| client.print @@headers | |
| client.print "UTC: #{Time.now.strftime("%Y-%m-%d %H:%M:%S")}" | |
| cities.compact.each do |city| | |
| client.puts "<p>#{city}: #{get_local_time_for(city)}</p>\r\n" | |
| end | |
| client.close | |
| end | |
| def go_threads | |
| Thread.start(@server.accept) do |client| | |
| massage client | |
| client.close | |
| end | |
| end | |
| def running_thread_count | |
| Thread.list.select {|thread| thread.status == "run"}.count | |
| end | |
| def run | |
| loop { | |
| puts running_thread_count | |
| if running_thread_count == 4 | |
| puts "BANG!! ITS PROCESS SPAWN!!!" | |
| Process.wait(fork do | |
| go_threads | |
| end) | |
| else | |
| go_threads | |
| end | |
| }.join | |
| end | |
| end | |
| server = Server.new('localhost', 3434) | |
| server.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment