Skip to content
Advertisement

Java ProxySelector undefined behaviour

I am experimenting with Proxies in java networking. I have read the documentation regarding them and am currently testing ProxySelector.

I notice 2 types of behaviour of this ProxySelector when using with HttpURLConnection & when using with Socket class

When using with HttpUrlConnection with this code

JavaScript

I get the expected output

JavaScript

This makes sense because ports 5000 & 8000 are just dummy ports with no server running on it hence connection fails on them and it finally goes to NO_PROXY which directly connects to my custom HttpServer running on port 2000 which returns not implemented for everything

Now i work with Sockets using the same procedure . Again i have verified that my server is running on port 2000

JavaScript

I get this output

JavaScript

This should not happen as the last option in the Proxy List is NO_PROXY which means direct connection without any proxy which should succeed but it seems that the ProxySelector never uses that last option in the list

Whats more bizarre is that if i change my ProxyType from SOCKS to HTTP as follows. I know it doesn’t make sense in this context but this is just for testing purposes

JavaScript

Then everything works

Output :

JavaScript

For some reason it skips all HTTP proxy types and not even test then.

I have used Sockets with Proxy.HTTP and it works perfectly as it issues an CONNECT command first before sending data.

Here is my dummy server i use for both these test cases

JavaScript

Why these differences? I am using jdk 17.0.2 with windows 10

Advertisement

Answer

This seems to be a bug in the JDK: JDK-7141231

Despite java.net.SocksSocketImpl in theory supporting proxy failover; in reality this does apparently not work because after the first failed connection attempt the socket is closed, but that same closed socket is used for any subsequent connection attemps, which therefore fail with “Socket closed” (which you are seeing).

The reason why changing the proxy type to HTTP “works” is because it performs a direct connection, ignoring all other specified proxies.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement