How do I connect to my Java server with a socket when the client applet/application runs behind a proxy/firewall?
I tried it with an applet, but it throws the "host unreachable" exception, among others.
You cannot connect because the client's proxy/firewall prevents most socket connections. Most firewalls prevent any kind of
communication, except for HTTP. This is done to protect the internal infrastructure; users can still browse the Web, but cannot
connect to other networked applications.
However, there are ways to connect your Java applications to Java servers through HTTP. This is sometimes called firewall tunneling. To do this easily, create servlets on the server side and wrap all client messages in HTTP requests.
On the client side, your code should use the URLConnection to send data to the server:
//connect
URL url = new URL("http://www.myserver.com/servlets/myservlet");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/octet-stream");
//Open output stream and send some data.
OutputStream out = conn.getOutputStream();
//I am not going to send anything on "out," but you can fill this in.
out.flush();
out.close();
//Open input stream and read the data back.
InputStream in = conn.getInputStream();
//Here you would read the data back.
in.close()
On the server side, when the client says openConnection(), the servlet's doPost() method will be called. In that method, you can read the data and write back to the client.