Skip to content
Snippets Groups Projects
YuHW2Server.java 2.51 KiB
package MV3500Cohort2024JulySeptember.homework2.Yu;

import java.io.IOException;
import java.net.*;

/**
 * @author Jin Hong Yu
 */
public class YuHW2Server
{
    /** Default constructor */
    public YuHW2Server()
    {
        // default constructor
    }
    /**
     * Program invocation, execution starts here
     * @param args command-line arguments
     */
    public static void main(String[] args)
    {
        try {
            ServerSocket             serverSocket = new ServerSocket(2317);
            Socket                   clientConnectionSocket;
            YuHW2HandlerThread handlerThread;

            int connectionCount = 0; // state variable

            //System.out.println(TcpExample4DispatchServer.class.getName() + " ready to accept socket connections...");
            while (true) // infinite loop
            {
                clientConnectionSocket = serverSocket.accept(); // block! until connected

                connectionCount++; // unblocked, got another connection
                
                
                System.out.println("=============================================================");
                //System.out.println(TcpExample4DispatchServer.class.getName() + ".handlerThread created for connection #" + connectionCount + "...");
                
                // hand off this aready-created and connected socket to constructor
                handlerThread = new YuHW2HandlerThread(clientConnectionSocket); 
                handlerThread.start();// invokes the run() method in that object
                //System.out.println(TcpExample4DispatchServer.class.getName() + ".handlerThread is now dispatched and running, using most recent connection...");
                
                // while(true) continue looping, serverSocket is still waiting for another customer client
            }
        } 
        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("============================================================="); // execution complete
    }
}