Java Reference
In-Depth Information
Example 5•9: Server.java (continued)
connected = false;
out.close();
in.close();
}
}
}
A Multithreaded Proxy Server
Example 5-6 demonstrated how to write a simple, single-threaded proxy server.
Example 5-10 uses the
Server
class and
Server.Service
interface defined in
Example 5-9 to implement a multithreaded proxy server. It demonstrates how you
can use the generic
Server
class to implement your own custom servers without
using the
main()
method of
Server
. The body of the inner
Proxy
class (which is
what implements the
Service
interface) is reminiscent of the
SimpleProxyServer
class but creates two anonymous threads instead of just one. The main thread uses
the
join()
method of the
Thread
class to wait for these two anonymous threads to
finish.
Example 5•10: ProxyServer.java
package com.davidflanagan.examples.net;
import java.io.*;
import java.net.*;
/**
* This class uses the Server class to provide a multi-threaded server
* framework for a relatively simple proxy service. The main() method
* starts up the server. The nested Proxy class implements the
* Server.Service interface and provides the proxy service.
**/
public class ProxyServer {
/**
* Create a Server object, and add Proxy service objects to it to provide
* proxy service as specified by the command-line arguments.
**/
public static void main(String[] args) {
try {
// Check number of args. Must be a multiple of 3 and > 0.
if ((args.length == 0) || (args.length % 3 != 0))
throw new IllegalArgumentException("Wrong number of args");
// Create the Server object
Server s = new Server(null, 12); // log stream, max connections
// Loop through the arguments parsing (host, remoteport, localport)
// tuples. For each, create a Proxy, and add it to the server.
int i = 0;
while(i < args.length) {
String host = args[i++];
int remoteport = Integer.parseInt(args[i++]);
int localport = Integer.parseInt(args[i++]);
s.addService(new Proxy(host, remoteport), localport);
}
}