⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httprequest.java

📁 基于TCP的java多线程server
💻 JAVA
字号:

import java.io.*;

import java.net.*;

import java.util.*;

final class HttpRequest extends Thread { //inherites from super class Thread for my second construtor
    static final String CRLF = "\r\n";
    Socket socket;
    String name;

    // Constructor
    public HttpRequest(Socket socket) throws Exception {
        this.socket = socket;
    }

	////the second construtor was used to get the thread name passed
	////from HttpRequest.java
    public HttpRequest(String str) throws Exception {
        super(str);
    }


    // Implement the run() method of the Runnable interface.
    public void run() {
        try {
            processRequest();
            //getRuntime();
            //output the thread name and its termination information.
            System.out.println("The condition of socket connection is " + socket.isClosed());

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

            System.out.println("*" + getName() + " is now completed" + "*");

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

        } catch (Exception e) {
            System.out.println(e);
        }

    }

    private void processRequest() throws Exception {
        try {
            // Get a reference to the socket's input and output streams.
            InputStream is = socket.getInputStream();

            DataOutputStream os =
                new DataOutputStream(socket.getOutputStream());

            // Set up input stream filters.
            //BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            // Get the request line of the HTTP request message.
            String requestLine = br.readLine();

            System.out.println("requestLine is "+requestLine);
            // Extract the filename from the request line.
            StringTokenizer tokens = new StringTokenizer(requestLine);
            tokens.nextToken(); // skip over the method, which should be "Request"
            String fileName = tokens.nextToken();

            // Prepend a "." so that file request is within the current directory.
            fileName = "." + fileName;
            System.out.println("File name is" + fileName);
            // Open the requested file.
            FileInputStream fis = null;
            boolean fileExists = true;
            try {
                fis = new FileInputStream(fileName);
            } catch (FileNotFoundException e) {
                fileExists = false;
                System.out.println("File name " + fileName + " not found");
            }

            // Debug info for private use

            String headerLine = null;
            while ((headerLine = br.readLine()).length() != 0) {
                System.out.println(headerLine);
            }

            // Construct the response message.
            String statusLine = null;
            String contentTypeLine = null;
            String entityBody = null;
            if (fileExists) {
                statusLine = "HTTP/1.0 200 Document Follows" + CRLF;
                contentTypeLine =
                        "Content-Type: " + contentType(fileName) + CRLF;

                //debug for outgoing data result and its content type part.
                System.out.println("\n\rOutgoing!");
                System.out.println("HTTP/1.0 200 ok");
                InetAddress addr = socket.getInetAddress();

                //System.out.println("The file was sending to IP: "+ socket.getInetAddress());

                System.out.println("Its host name: "+ addr.getHostName());

                System.out.println(contentTypeLine);
            } else {
                statusLine = "HTTP/1.0 200 Document listed" + CRLF;
                //contentTypeLine = "Content-Type: " + contentType(fileName) + CRLF;
                contentTypeLine =
                        //"Content-Type is : text/html; charset=utf-8" + CRLF;
                	contentType(fileName) + CRLF;
                entityBody =
                        "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>" +
                        "<BODY>Not Found, This problem may be caused by wrong file name or exstension.</BODY></HTML>";

                //debug for outgoing data result and its content type part.
                System.out.println("\n\rOutgoing!");
                System.out.println("HTTP/1.0 404 Not Found");
                System.out.println(contentTypeLine);
            }

            // Send the status line.
            os.writeBytes(statusLine);

            // Send the content type line.
            os.writeBytes(contentTypeLine);

            // Send a blank line to indicate the end of the header lines.
            os.writeBytes(CRLF);

            // Send the entity body.
            if (fileExists) {
                //System.out.println("fileExists");
                sendBytes(fis, os);
                fis.close();
                System.out.println("File name" + fileName +
                                   " exist");
            } else {
                System.out.println("File name" + fileName +
                                   " does not exist.");
                os.writeBytes(entityBody);
            }

            // Close streams and socket.
            os.close();
            br.close();
            socket.close();

            //System.out.println("Is socket closed?" + socket.isClosed());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private static void sendBytes(FileInputStream fis,
                                  OutputStream os) throws Exception {
        try {
            // Construct a 1K buffer to hold bytes on their way to the socket.
            byte[] buffer = new byte[1024];
            int bytes = 0;

            // Copy requested file into the socket's output stream.
            while ((bytes = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytes);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }


    private static String contentType(String fileName) {
        try {
			//Three content types below
            if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
                return "text/html";
            }
            if (fileName.endsWith(".jpg")) {
                return "image/jpeg";
            }
            if (fileName.endsWith(".mp3")) {
                return "sound/mp3";
            ////situation when there is unknown file extension entered other than
            ////above three types.
            } else {
                return "Unknown file extension";
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return "application/octet-stream";
    }
}

⌨️ 快捷键说明

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