Search code examples
rubyseleniumphantomjsjrubywatir

Connection refuse Watir webdriver with phantomjs


I have a problem with Watir gem that is running in threads. Basically it looks like this: I am creating threads (let's say there are three of them). Then I am creating new browser, visiting web pages and trying to close this browser. Everything works fine for like 2-3 hours, then I am getting this error (browser.close is causing this):

Errno::ECONNREFUSED: Connection refused - Connection refused
       initialize at org/jruby/ext/socket/RubyTCPSocket.java:124
             open at org/jruby/RubyIO.java:1123
 block in connect at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:883
          timeout at org/jruby/ext/timeout/Timeout.java:128
          connect at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:882
         do_start at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:867
            start at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:856
            start at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:583
             stop at /home/ubuntu/.rvm/gems/jruby-9.0.4.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/phantomjs/service.rb:75
             quit at /home/ubuntu/.rvm/gems/jruby-9.0.4.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/phantomjs/bridge.rb:73
             quit at /home/ubuntu/.rvm/gems/jruby-9.0.4.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/common/driver.rb:171
            close at /home/ubuntu/.rvm/gems/jruby-9.0.4.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/browser.rb:136

And this is the code:

THREAD_COUNT.times.map {
  Thread.new(links) do |links|
    while link = mutex.synchronize { links.pop }
      counter = 0
      sleep(rand 1..50)
      browser = Watir::Browser.new :phantomjs, :args => %w(--ssl-protocol=tlsv1 --ignore-ssl-errors=yes)
      begin
       result = function(browser)
      rescue
       counter += 1
       retry if counter > 2
      end
      browser.close
    end
  end
}.each(&:join)

I am running this on ubuntu and jruby 9.0.4.0 As suggested here, I added sleep Opening several threads with watir-webdriver results in 'Connection refused' error But it's not working


Solution

  • As you can see, I was creating new browser instance in while-loop. Sometimes it just couldn't close that browser on time or other pid-related glitches occured. It's better to create fixed amount of browsers (for example THREAD_COUNT times) and reuse it when it's available. So creating browser right after THREAD_COUNT.times.map will give you one browser instance for each thread.