File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Sockets and Internet Protocols and the fly likes Connecting Sockets thru Proxy Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Connecting Sockets thru Proxy" Watch "Connecting Sockets thru Proxy" New topic
Author

Connecting Sockets thru Proxy

Gopal Shah
Ranch Hand

Joined: May 17, 2003
Posts: 65
Hi All,
I am trying to make socket connections thru a local firewall, for which I am setting the proxy host and port num.
I tried the method described in the following link
Getting through a Proxy with Sockets
But somehow I was unsuccessful to do so. Using the URLConnection approach it works i.e. when I do the

or its equivalent mentioned in link above.
But for sockets it doesn't work, although I am trying to connect to the http port only. I even tried reading the source code of URL and its related classes -> URLConnection, etc. but it looks like URLConnection doesn't use the socket abstraction (Socket class in Java) and instead uses native methods to connect thru OS level sockets. Correct me if I am wrong in my understanding.
In Java API doc, its written
An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

Will this method work ? If yes how do we write custom socket factory ?
Thanks and regards,
Gopal
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
I have a guess as to why Socket(host, port) fails with Connection refused. Does this make sense?
----
This is how I see the problem:
This works:
URL u = new URL(http://java.sun.com);
URLConnection uc = u.openConnection();

But this does not work:
InetAddress addr = new InetAddress(http://java.sun.com);
Socket s = new (addr, 80);
This is the exception:
java.net.ConnectException: Connection refused: connect
----
When I do this:
URL u = new URL(host);
URLConnection uc = u.openConnection();
System.out.println(uc.getClass());
I get this:
class sun.net.www.protocol.http.HttpURLConnection
----
Here is my explanation. Does this make sense?
sun.net.www.protocol.http.HttpURLConnection is a subclass of the abstract class URLConnection. Sun must implement the abstract method URLConnection.connect().
I am guessing, when Sun implements connect(), Sun is calling Socket(host, port) with host and port of the proxy server. Sun is negotiating with the proxy server using the HTTP protocol.
[ March 03, 2004: Message edited by: Marlene Miller ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Connecting Sockets thru Proxy