Java Reference
In-Depth Information
the main thread reads bytes from the server and sends them to the client. A sepa-
rate thread reads bytes from the client and sends them to the server. In Java 1.3
and earlier, if you want to monitor multiple streams, as we do here, you have to
use multiple threads: Java doesn't support nonblocking I/O, nor does it define any
way to block on multiple streams at the same time. Using one thread per stream
can cause scalability problems for busy servers, however, so this limitation may be
remedied in Java 1.4.
Example 5•6: SimpleProxyServer.java
package com.davidflanagan.examples.net;
import java.io.*;
import java.net.*;
/**
* This class implements a simple single-threaded proxy server.
**/
public class SimpleProxyServer {
/** The main method parses arguments and passes them to runServer */
public static void main(String[] args) throws IOException {
try {
// Check the number of arguments
if (args.length != 3)
throw new IllegalArgumentException("Wrong number of args.");
// Get the command-line arguments: the host and port we are proxy
// for and the local port that we listen for connections on.
String host = args[0];
int remoteport = Integer.parseInt(args[1]);
int localport = Integer.parseInt(args[2]);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" +
remoteport + " on port " + localport);
// And start running the server
runServer(host, remoteport, localport);
// never returns
}
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java SimpleProxyServer " +
"<host> <remoteport> <localport>");
}
}
/**
* This method runs a single-threaded proxy server for
* host:remoteport on the specified local port. It never returns.
**/
public static void runServer(String host, int remoteport, int localport)
throws IOException {
// Create a ServerSocket to listen for connections with
ServerSocket ss = new ServerSocket(localport);
// Create buffers for client-to-server and server-to-client transfer.
// We make one final so it can be used in an anonymous class below.
// Note the assumptions about the volume of traffic in each direction.
final byte[] request = new byte[1024];
byte[] reply = new byte[4096];
// This is a server that never returns, so enter an infinite loop.
Search WWH ::




Custom Search