Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

ruby - 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...