Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening several threads with watir-webdriver results in 'Connection refused' error

I have this simple example:

require 'watir-webdriver'

arr = []
sites = [
"www.google.com",
"www.bbc.com",
"www.cnn.com",
"www.gmail.com"
]

sites.each do |site|
    arr << Thread.new {
        b = Watir::Browser.new :chrome
        b.goto site
        puts b.url
        b.close
    }
end
arr.each {|t| t.join}

Every time i run this script, I get

ruby/2.1.0/net/http.rb:879:in `initialize': Connection refused - connect(2) for "127.0.0.1"      port 9517 (Errno::ECONNREFUSED)

Or one of the browsers closes unexpectedly on atleast one of the threads.

on the other hand, if i set sleep 2 at the end of every loop cycle, everything runs smoothly! Any idea why is that?

Must be something related to understanding how threads work...

like image 240
MichaelR Avatar asked Nov 11 '14 07:11

MichaelR


1 Answers

You're basically creating a race condition between the instances of your browser to connect to the open port watir-webdriver is finding. In this case, your first instance of the browser sees that port 9517 is open and connects to it. Because you're spinning up these instances in parallel, your second instance also thinks port 9517 is open and tries to connect. But oops, that port is already being used by the first browser instance. That's why you get this particular error.

This also explains why the sleep 2 fixes the issue. The first browser instance connects to port 9517 and the sleep causes the second browser instance to see that 9517 is taken. It then connects on port 9518.

EDIT

You can see how this is implemented with Selenium::WebDriver::Chrome::Service#initialize (here), which calls Selenium::WebDriver::PortProber (here). PortProber is how the webdriver determines which port is open.

like image 109
Johnson Avatar answered Sep 24 '22 23:09

Johnson