import java.net.*;
import java.io.*;
import java.lang.*;
// A generic server which listens on a port and connects to any clients it
// finds. Made to extend thread, so that an application can have multiple
// server threads servicing several ports, if necessary.
// NOTE: This file contains incomplete example code only, which will
// not compile without additions and modifications.
public class GenServer extends Thread
{
protected int portNo; // Port to listen to for clients
protected ServerSocket clientConnect;
protected ClientConnection connExemplar;
// Exemplar connection to make with clients
public GenServer(int port) throws IllegalArgumentException
{
if (port <= 0)
throw new IllegalArgumentException(
"Bad port number given to GenServer constructor.");
// Try making a ServerSocket to the given port
try { clientConnect = new ServerSocket(port); }
catch (IOException e)
{
System.out.println("Failed to connect to port " + port);
System.exit(1);
}
// Made the connection, so set the local port number
this.portNo = port;
this.connExemplar = new DummyClientConnection();
}
public void setConnectionType(ClientConnection c)
{
this.connExemplar = c;
}
public void run()
{
// Listen to port for client connection requests. For each one,
// attach a ClientConnection generated from our exemplar.
try
{
while (true)
{
Socket clientReq = clientConnect.accept();
ClientConnection c = conExemplar.newConnection();
c.Connect(clientReq);
}
}
catch (IOException e)
{
System.out.println("IO exception while listening for clients.");
System.exit(1);
}
}
// Main routine - start the server on the given port with the specified
// ClientConnection subclass.
public static void main(String[] argv)
{
int port;
Class connectClass;
ClientConnection clientType;
ClassLoader loader = System.getClassLoader();
// Get the requested port number off of the command line, if present
if (args.length >= 1)
port = Integer.parseInt(argv[0]);
else
port = 0;
// Get the client connection class from the command line, if present
if (args.length >= 2)
{
connectClass = loader.loadClass(argv[1]);
try
{
clientType = (ClientConnection)connectClass.newInstance();
}
catch (ClassCastException e)
{
System.out.println("Given class name " + argv[1]
+ " not a ClientConnection subclass. Using default.");
clientType = new DummyClientConnection();
}
}
else
clientType = new DummyClientConnection();
// Connect a server to the port, and set the client type.
GenServer gs = new GenServer(port);
gs.setConnectionType(clientType);
gs.run();
}
} |