Java Reference
In-Depth Information
Example 5•10: ProxyServer.java (continued)
catch (Exception e) { // Print an error message if anything goes wrong
System.err.println(e);
System.err.println("Usage: java ProxyServer " +
"<host> <remoteport> <localport> ...");
System.exit(1);
}
}
/**
* This is the class that implements the proxy service. The serve() method
* will be called when the client has connected. At that point, it must
* establish a connection to the server, and then transfer bytes back and
* forth between client and server. For symmetry, this class implements
* two very similar threads as anonymous classes. One thread copies bytes
* from client to server, and the other copies them from server to client.
* The thread that invoke the serve() method creates and starts these
* threads, then just sits and waits for them to exit.
**/
public static class Proxy implements Server.Service {
String host;
int port;
/** Remember the host and port we are a proxy for */
public Proxy(String host, int port) {
this.host = host;
this.port = port;
}
/** The server invokes this method when a client connects. */
public void serve(InputStream in, OutputStream out) {
// These are some sockets we'll use. They are final so they can
// be used by the anonymous classes defined below.
final InputStream from_client = in;
final OutputStream to_client = out;
final InputStream from_server;
final OutputStream to_server;
// Try to establish a connection to the specified server and port
// and get sockets to talk to it. Tell our client if we fail.
final Socket server;
try {
server = new Socket(host, port);
from_server = server.getInputStream();
to_server = server.getOutputStream();
}
catch (Exception e) {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
pw.print("Proxy server could not connect to " + host +
":" + port + "\n");
pw.flush();
pw.close();
try { in.close(); } catch (IOException ex) {}
return;
}
// Create an array to hold two Threads. It is declared final so
// that it can be used by the anonymous classes below. We use an
// array instead of two variables because given the structure of
Search WWH ::




Custom Search