package TcpExamples; import java.io.IOException; import java.net.*; /** * A server example that creates and dispatches a new thread to handle multiple * connections one after another, running in parallel. * * @author Don McGregor * @author Don Brutzman * @author MV3500 class */ public class TcpExample4DispatchServer { /** * Program invocation, execution starts here * @param args command-line arguments */ public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(2317); TcpExample4HandlerThread handlerThread; Socket clientConnection; int connectionCount = 0; // state variable System.out.println(TcpExample4DispatchServer.class.getName() + " ready to accept socket connections..."); while (true) // infinite loop { clientConnection = serverSocket.accept(); // block until connected connectionCount++; // unblocked, got another connection System.out.println("============================================================="); System.out.println(TcpExample4DispatchServer.class.getName() + ".handlerThread invocation for connection #" + connectionCount + "..."); handlerThread = new TcpExample4HandlerThread(clientConnection); handlerThread.start(); // invokes the run() method in that object System.out.println(TcpExample4DispatchServer.class.getName() + ".handlerThread is launched, awaiting another connection..."); } } catch (IOException e) { System.out.println("Problem with " + TcpExample4DispatchServer.class.getName() + " networking:"); // describe what is happening System.out.println("Error: " + e); // Provide more helpful information to user if exception occurs due to running twice at one time if (e instanceof java.net.BindException) { System.out.println("*** Be sure to stop any other running instances of programs using this port!"); } } System.out.println("============================================================="); } }