0

I'm occurring some trouble writing a basic webserver in JAVA. It's currently working fine at delivering html or css files. But when it comes to images things are messed up. I assume I'm doing something wrong at reading the image-files and preparing them to be sent. But have a look at the code:

public void launch()
{
    while(true)
    {
        try
        {
             Socket connection = this.server_socket.accept();

             ...

             PrintWriter print_writer = new PrintWriter(connection.getOutputStream());

             String response = this.readFile(this.request_header.get("Resource"));
             print_writer.print(response);

             print_writer.flush();
             connection.close();
         }
         catch(...)
         {
             ...
         }
    }
}

private String readFile(String path)
{
    try
    {
         ...

         FileInputStream file_input_stream = new FileInputStream(path);         
         int bytes = file_input_stream.available();
         byte[] response_body = new byte[bytes];

         file_input_stream.read(response_body);
         this.response_body = new String(response_body);

         file_input_stream.close();

         this.setResponseHeader(200, file_ext);

         this.response_header = this.response_header + "\r\n\r\n" + this.response_body;
    }
    catch(...)
    {
         ...
    }

    return this.response_header;
}

So my browser receives something like:

HTTP/1.0 200 OK
Content-type: image/jpeg

[String that was read in readFile()]

But chrome's not displaying the image correctly and opera won't show it all! I used to read the file with an BufferedReader but I found someone saying that the BufferedReader can't handle binary data properly so I tried with the FileInputStream, but the problem stayed the same ):

Thanks for any hints and help in advance (:

1 Answer 1

2

You must use streams on both sides: input stream and output stream. Readers and writers assume the content is Unicode and make adjustments to the byte stream. PrintWriter is, of course, a writer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.