【问题标题】:How can i send correctly the name of the file, which i need to GET via GET-method to local server?如何正确发送文件名,我需要通过 GET 方法将其发送到本地服务器?
【发布时间】:2019-05-20 07:53:15
【问题描述】:

我已经编写了一个简单的 HTTP 服务器和一个客户端。我需要实现简单的 GET 方法并传输一个文件名,我想在我的服务器页面和控制台中打印它。我写了,但它不起作用。

我将一个字符串传输到服务器,然后服务器正在解析,尝试找出文件名。我用substring。 我有一个名为“site.html”的简单 html 页面,我需要打印出来。

public class Client {
     public static void main(String[] args) throws IOException{
        System.out.println("Enter IP and port: ");

        Scanner in = new Scanner(System.in);
        String ip = in.next();

        int port = in.nextInt();
        System.out.println("Enter name of the file");
        String name_of_File = in.next();

        System.out.println(name_of_File);       //no usage

        Socket clientSocket = new Socket(InetAddress.getByName(ip), port);
        Client client = new Client(clientSocket);

        client.writeOutputStream(name_of_File);
        client.readInputStream();
    }

    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public Client(Socket socket) throws IOException {
        this.socket = socket;
        this.inputStream = socket.getInputStream();
        this.outputStream = socket.getOutputStream();
    }

    public void writeOutputStream(String fileName) throws IOException {             //getter
        String getter = "GET / HTTP/1.1\n" +"File: " + fileName + ":"+"\n\n";
        outputStream.write(getter.getBytes());
        outputStream.flush();

    }

    public void readInputStream() throws IOException {      //console output from server
        Scanner scan = new Scanner(inputStream);
        String str;
        while (scan.hasNextLine()){
            str = scan.nextLine();
            System.out.println(str);
        }

    }
}

这里有服务器

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);

        while (true) {
            System.out.println("Waiting for a client connection...");

            Socket clientSocket = serverSocket.accept();
            Server server = new Server(clientSocket);
            System.out.println("Client has connected successfully");
            server.readInputStream();
            server.writeOutputStream();
            server.clientSocket.close();
        }
    }
    public Socket clientSocket;
    private InputStream inputStream;
    private OutputStream outputStream;
    private String fileName;

    public Server(Socket clientSocket) throws IOException {
        this.clientSocket = clientSocket;
        this.inputStream = clientSocket.getInputStream();
        this.outputStream = clientSocket.getOutputStream();
       // this.fileName = "site.html";
    }

    public void readInputStream() throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();

        sb.append(in.readLine());       //first line is a method(GET-method here)
        while (in.readLine() != null || in.readLine().trim().length() != 0) {
            String str = in.readLine();
            sb.append(str);
            if(str.contains(".html")) {
                fileName = str.substring(str.indexOf("File:") + 5, str.length() - str.lastIndexOf("html") + 4);
                System.out.println(fileName);
            }
        }

    }
    //String name_of_File = in.findInLine(Pattern.compile(".....html"));
    public void writeOutputStream() throws IOException {
        File file = new File(fileName);

        if (file.exists()) {        //reading "site.html"
            String s = new String(Files.readAllBytes(Paths.get(fileName)));
            String response = "HTTP/1.1 200 OK\n" +
                    "Type: text/html\n" +
                    "Length: " + s.length() + "\n" +
                    "Closing connection\n\n" + s;
            outputStream.write(response.getBytes());
            outputStream.flush();
        }
        else {
            outputStream.write("<html><h2>404:file not found</h2></html>".getBytes());
            outputStream.flush();
        }

    }
}

我希望看到打印的页面,但没有发生。

【问题讨论】:

    标签: java http server client


    【解决方案1】:

    问题在于服务器中的 readLine() 方法,位于 readInputStream() 方法下。它不会读取超出字符串中“HTTP/1.1\n”之后的换行符 (\n) 字符。

    在这里,我修改了readInputStream() 方法的代码。我正在使用read() 方法,并且我还更改了子字符串的索引。在此之前,您的代码试图在 start index: 21end index: 8 处显示子字符串,因为您要从字符串长度中减去结束索引。修改后的方法:

    public void readInputStream() throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        int i;
        // read the inputStream character by character
        while ((i = in.read()) != -1) {
            char ch = (char)i;
            String str = Character.toString(ch);
            sb.append(str);
            str = sb.toString();
            if(str.contains(".html")) {
                // modified substring indices
                fileName = str.substring(str.indexOf("File:") + 6, str.lastIndexOf("html") + 4);
                System.out.println("\n"+fileName);
                break;
            }
        }
    }
    

    SERVER 端的输出如下所示:

    Waiting for a client connection...
    Client has connected successfully
    Entered the readInputStream() method.
    
    site.html
    Waiting for a client connection...
    

    CLIENT 端的输出如下所示:

    Enter IP and port: 
    127.0.0.1
    8080
    Enter name of the file
    site.html
    GET / HTTP/1.1
    File: site.html:
    
    
    <html><h2>404:file not found</h2></html>
    
    Process finished with exit code 0
    

    如果您在正确的位置创建了文件路径,则该文件路径应该可以在您的系统上使用。

    你也可以看看这个答案here,它建议使用read()来逐个字符地读取你的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-26
      • 2021-10-13
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2014-05-10
      • 2014-09-09
      • 2013-09-24
      相关资源
      最近更新 更多