Created
March 7, 2017 09:51
-
-
Save anke1460/0785f9e18b8ebd34ff2de607178fa7b2 to your computer and use it in GitHub Desktop.
server.rb
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 'net/http' | |
| require 'json' | |
| require 'drb' | |
| require 'logger' | |
| require 'singleton' | |
| class Server | |
| include Singleton | |
| def log | |
| @log ||= Logger.new('log') | |
| @log | |
| end | |
| def results | |
| @mutex.synchronize do | |
| if @expire.nil? || (Time.now - @expire) > 30 | |
| @time = Time.now | |
| @expire = @time + 30 | |
| @remote_response = JSON.parse(Net::HTTP.get(URI.parse('http://pythoninterview.ulaiber.com'))) | |
| reset_index | |
| @token = @remote_response["token"] | |
| @results = @remote_response["result"].split('').permutation.map(&:join) | |
| end | |
| @request_num += 1 | |
| if @request_num <= @capacity | |
| log.info "Client ip #{Thread.current['DRb']['client'].peeraddr[2]}, current key #{@results[@index]}, current index #{@index}" | |
| key = @results[@index] | |
| @index += 1 | |
| @request_num -= 1 | |
| key | |
| else | |
| log.info "Failure, client ip #{Thread.current['DRb']['client'].peeraddr[2]}, current is #{@results[@index]}, index is #{@index}" | |
| nil | |
| end | |
| end | |
| end | |
| def current | |
| @request_num | |
| end | |
| def reset_index | |
| @index = 0 | |
| end | |
| def get_result | |
| @key | |
| end | |
| def reset | |
| @expire = nil | |
| end | |
| def index | |
| @index | |
| end | |
| def success!(result) | |
| log.info "Hi, i found the key is result" | |
| @key = result | |
| @is_find = true | |
| end | |
| def is_find? | |
| @is_find | |
| end | |
| def get_token | |
| @token | |
| end | |
| def time | |
| (Time.now - @time).to_i | |
| end | |
| private | |
| def initialize | |
| @capacity = 500 | |
| @expire = nil | |
| @results = [] | |
| @token = '' | |
| @key = '' | |
| @request_num = 0 | |
| @mutex = Mutex.new | |
| @is_find = false | |
| @time = 0 | |
| end | |
| end | |
| DRb.start_service 'druby://120.27.139.130:9000', Server.instance | |
| DRb.thread.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment