0

I have written a simple HTTP-server and a client. I need to implement simple GET-method and transfer a file name, which i want to print in my server page and in my console. I written it, but it does not work.

I transfer a string to server, which then server is parsing, try to find out the file name. I used substring. I have simple html page called "site.html", which i need to print out.

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);
        }

    }
}

AND SERVER HERE

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();
        }

    }
}

I expected to see printed page, but it does not happen.

taciturno
  • 175
  • 2
  • 10

1 Answers1

0

The problem is with the readLine() method in your server, under the readInputStream() method. It does not read beyond the newline (\n) character in your string, after "HTTP/1.1\n".

Here, I have modified your code for the readInputStream() method. I am using the read() method and I have also changed the indices of the substring. Before this, your code was trying to display a substring at a start index: 21 and end index: 8, because you were subtracting the end index from the string length. The modified method:

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;
        }
    }
}

The output at the SERVER end looks like so:

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

site.html
Waiting for a client connection...

The output at the CLIENT end looks like this:

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

The file path should work on your system if you have it created at the right location.

You can also take a look at this answer here, which suggests using read() instead, to read your string character by character.

Rachayita Giri
  • 487
  • 5
  • 17