当本地主机: 从浏览器调用时,如何重定向到本地存储的index.html文件

问题描述 投票:0回答:1

我正在用android创建套接字服务器。我的本地存储中有一个目录,其中有index.html和所有其他资源。我希望在启动套接字服务器然后从移动设备的浏览器调用localhost:时将其重定向到index.html。我的套接字正在运行。日志正在打印。问题是我不知道如何重定向到index.html。预先感谢。

下面是我的代码:

public class Server {
MainActivity activity;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;

public Server(MainActivity activity) {
    this.activity = activity;
    Thread socketServerThread = new Thread(new SocketServerThread());
    socketServerThread.start();
}

public int getPort() {
    return socketServerPORT;
}

public void onDestroy() {
    if (serverSocket != null) {
        try {
            serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private class SocketServerThread extends Thread {

    int count = 0;

    @Override
    public void run() {
        try {
            // create ServerSocket using specified port
            serverSocket = new ServerSocket(socketServerPORT);

            while (true) {
                // block the call until connection is created and return
                // Socket object
                Socket socket = serverSocket.accept();
                count++;
                message += "#" + count + " from "
                        + socket.getInetAddress() + ":"
                        + socket.getPort() + "\n";

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("SocketServerThread.run i am running");
                    }
                });

                SocketServerReplyThread socketServerReplyThread =
                        new SocketServerReplyThread(socket, count);
                socketServerReplyThread.run();

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private class SocketServerReplyThread extends Thread {

    private Socket hostThreadSocket;
    int cnt;

    SocketServerReplyThread(Socket socket, int c) {
        hostThreadSocket = socket;
        cnt = c;
    }

    @Override
    public void run() {
        OutputStream outputStream;

        String msgReply = "Hello from Server, you are #" + cnt;
          final String OUTPUT = "https://www.google.com";
          final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/html; charset=UTF-8\r\n" +
                  "date: Fri, 25 Oct 2019 04:58:29 GMT"+
                "Content-Length: ";
             final String OUTPUT_END_OF_HEADERS = "\r\n\r\n";
        try {
            outputStream = hostThreadSocket.getOutputStream();
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(
                            new BufferedOutputStream(outputStream),"UTF-8" ));

                    out.write(OUTPUT_HEADERS + OUTPUT.length() + OUTPUT_END_OF_HEADERS + OUTPUT);

            out.flush();
            out.close();

            return;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            message += "Something wrong! " + e.toString() + "\n";
        }
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                System.out.println("Here is another message for you " + message);
            }
        });
    }
}

public String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress
                        .nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += "Server running at : "
                            + inetAddress.getHostAddress();
                }
            }
        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }
    return ip;
}
}
java android server localhost serversocket
1个回答
0
投票

最后我在这里找到了解决我问题的方法

   static final File WEB_ROOT = new File("<your files path>");
static final String DEFAULT_FILE = "index.html";
static final String FILE_NOT_FOUND = "404.html";
static final String METHOD_NOT_SUPPORTED = "not_supported.html";

  private class SocketServerThread extends Thread {

    int count = 0;

    @Override
    public void run() {
        try {
            // create ServerSocket using specified port
            serverSocket = new ServerSocket(socketServerPORT);
                while (true) {
                // block the call until connection is created and return
                // Socket object
                Socket socket = serverSocket.accept();
                connect = socket;
                count++;
                message += "#" + count + " from "
                        + socket.getInetAddress() + ":"
                        + socket.getPort() + "\n";

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("SocketServerThread.run i am running");
                    }
                });

                JavaHTTPServer.SocketServerReplyThread socketServerReplyThread =
                        new JavaHTTPServer.SocketServerReplyThread(socket, count);
                socketServerReplyThread.run();

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private class SocketServerReplyThread extends Thread {

    private Socket hostThreadSocket;
    int cnt;

    SocketServerReplyThread(Socket socket, int c) {
        hostThreadSocket = socket;
        cnt = c;
    }

    @Override
    public void run() {// we manage our particular client connection
        BufferedReader in = null;
        PrintWriter out = null;
        BufferedOutputStream dataOut = null;
        String fileRequested = null;

        try {
            // we read characters from the client via input stream on the socket
            in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
            // we get character output stream to client (for headers)
            out = new PrintWriter(connect.getOutputStream());
            // get binary output stream to client (for requested data)
            dataOut = new BufferedOutputStream(connect.getOutputStream());

            // get first line of the request from the client
            String input = in.readLine();
            System.out.println("SocketServerReplyThread.run input " + input);
            // we parse the request with a string tokenizer
            if (input == null)
                return;
            StringTokenizer parse = new StringTokenizer(input);
            System.out.println("SocketServerReplyThread.run parse " + parse);
            String method = parse.nextToken().toUpperCase(); // we get the HTTP method of the client
            System.out.println("SocketServerReplyThread.run method " + method);
            // we get file requested
            fileRequested = parse.nextToken().toLowerCase();
            if (fileRequested.contains("?"))
                fileRequested = fileRequested.split("\\?")[0];

            System.out.println("SocketServerReplyThread.run fileRequested " + fileRequested);
            // we support only GET and HEAD methods, we check
            if (!method.equals("GET") && !method.equals("HEAD")) {
                if (verbose) {
                    System.out.println("501 Not Implemented : " + method + " method.");
                }

                // we return the not supported file to the client
                File file = new File(WEB_ROOT, METHOD_NOT_SUPPORTED);
                int fileLength = (int) file.length();
                String contentMimeType = "text/html";
                //read content to return to client
                byte[] fileData = readFileData(file, fileLength);

                // we send HTTP Headers with data to client
                out.println("HTTP/1.1 501 Not Implemented");
                out.println("Server: Java HTTP Server from SSaurel : 1.0");
                out.println("Date: " + new Date());
                out.println("Content-type: " + contentMimeType);
                out.println("Content-length: " + fileLength);
                out.println(); // blank line between headers and content, very important !
                out.flush(); // flush character output stream buffer
                // file
                dataOut.write(fileData, 0, fileLength);
                dataOut.flush();

            } else {
                // GET or HEAD method
                if (fileRequested.endsWith("/")) {
                    fileRequested += DEFAULT_FILE;
                }

                File file = new File(WEB_ROOT, fileRequested);
                int fileLength = (int) file.length();
                String content = getContentType(fileRequested);

                if (method.equals("GET")) { // GET method so we return content
                    byte[] fileData = readFileData(file, fileLength);

                    // send HTTP Headers
                    out.println("HTTP/1.1 200 OK");
                    out.println("Server: Java HTTP Server from SSaurel : 1.0");
                    out.println("Date: " + new Date());
                    out.println("Content-type: " + content);
                    out.println("Content-length: " + fileLength);
                    out.println(); // blank line between headers and content, very important !
                    out.flush(); // flush character output stream buffer

                    dataOut.write(fileData, 0, fileLength);
                    dataOut.flush();
                }

                if (verbose) {
                    System.out.println("File " + fileRequested + " of type " + content + " returned");
                }

            }

        } catch (FileNotFoundException fnfe) {
            try {
                fileNotFound(out, dataOut, fileRequested);
            } catch (IOException ioe) {
                ioe.printStackTrace();
                System.err.println("Error with file not found exception : " + ioe.getMessage());
            }

        } catch (IOException ioe) {
            System.err.println("Server error : " + ioe);
        } finally {
            try {
                in.close();
                out.close();
                dataOut.close();
                connect.close(); // we close socket connection
            } catch (Exception e) {
                System.err.println("Error closing stream : " + e.getMessage());
            }

            if (verbose) {
                System.out.println("Connection closed.\n");
            }
        }

    }
}


private byte[] readFileData(File file, int fileLength) throws IOException {
    FileInputStream fileIn = null;
    byte[] fileData = new byte[fileLength];

    try {
        fileIn = new FileInputStream(file);
        fileIn.read(fileData);
    } finally {
        if (fileIn != null)
            fileIn.close();
    }

    return fileData;
}

// return supported MIME Types
private String getContentType(String fileRequested) {
    if (fileRequested.endsWith(".htm") || fileRequested.endsWith(".html"))
        return "text/html";
    else
        return "text/plain";
}

private void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
    File file = new File(WEB_ROOT, FILE_NOT_FOUND);
    int fileLength = (int) file.length();
    String content = "text/html";
    byte[] fileData = readFileData(file, fileLength);

    out.println("HTTP/1.1 404 File Not Found");
    out.println("Server: Java HTTP Server from SSaurel : 1.0");
    out.println("Date: " + new Date());
    out.println("Content-type: " + content);
    out.println("Content-length: " + fileLength);
    out.println(); // blank line between headers and content, very important !
    out.flush(); // flush character output stream buffer

    dataOut.write(fileData, 0, fileLength);
    dataOut.flush();

    if (verbose) {
        System.out.println("File " + fileRequested + " not found");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.