webserver.java

来自「基于TCP的java多线程server」· Java 代码 · 共 76 行

JAVA
76
字号

import java.io.*;

import java.net.*;

import java.util.*;


public final class WebServer {
    public static void main(String[] argv) throws Exception {

        try {
            // Get the port number from the command line.
           int port = (new Integer(argv[0])).intValue();

            // Establish the listen socket.
            Socket connectionSocket;

			////ServerSocket listenSocket;
            ServerSocket listenSocket = new ServerSocket(port);

            // Process HTTP service requests in an infinite loop.
            while (true) {

                // Listen for a TCP connection request.
                connectionSocket = listenSocket.accept();

                // Construct an object to process the HTTP request message.
                ////create an instance of HttpRequest.
                HttpRequest thread = new HttpRequest(connectionSocket);

                ////create an instance for the second constructor so that
                ////the thread name can be retrieved in HttpRequest.java later on.
                ////HttpRequest request1 = new HttpRequest("");

                System.out.println("******************");

                // Start the thread.
                thread.start();

				////for debugging use, see the thread information.
                System.out.println("*" + thread.getName() + " is beginning" + "*");

                System.out.println("******************");

                System.out.println("The Port Number is:  " + port);

                System.out.println("Thead started working is:  " + thread.isAlive());

                 //// System.out.println("Thread state is: " + thread.getState());

            }

            /* Although using (Exception e) could fulfill all other means of
            * exception handling, it is sometimes too vague for the error information.
            * As a result, I have specified different types of exception so that
            * the user could get a more detailed message.
            */
        } catch (IOException e) {
            System.out.println("Caught by Exception Handling!" +
                               "\r\nError: " + e);
        } catch (IllegalArgumentException e) {
            System.out.println("Caught by Exception Handling! Failed to establish port!" +
                               "\r\nError: " + e);
        } catch (SecurityException e) {
            System.out.println("Caught by Exception Handling!" +
                               "\r\nError: " + e);
        } catch (Throwable e) {
            System.out.println("Caught by Exception Handling!" +
                               "\r\nError: " + e);
        }

    }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?