简体   繁体   中英

Sending image (or binary data) over sockets in Java

I am writing an HTTP server for fun from scratch (trying to learn HTTP more indepth) and have gotten the server to send to the client an HTTP response with HTML without much of an issue.

The problem comes when I try to send binary data such as a JPEG image over the wire. The browser cannot seem to be interpreting it correctly. I have set the MIME type of my response to image/jpeg for this, and along with the correct Content-Length , I am still not able to correctly transmit the data.

A bit stumped on this and was wondering if maybe my understanding or approach to how binary data is read in Java is incorrect?

The general approach I am doing is I am reading the file from disk into a FileInputStream and then reading the data into a 1024 byte buffer. As I am reading into the buffer, I am writing the buffered data into a DataOutputStream which has the client's socket connection as the OutputStream . I am flushing and closing the data after using it.

The portion in which I am generating my body for my HTTP response is here:

        FileInputStream fis = new FileInputStream("www/server.jpg");
        byte[] buffer = new byte[1024];
        DataOutputStream dos = new DataOutputStream(this.clientSocket.getOutputStream());
        int read;
        while((read=fis.read(buffer)) >= 0) {
            dos.write(buffer, 0, read);
        }

        dos.flush();

        fis.close();
        dos.close();

I have hardcoded a few things, but I think this generally gets my question across. So, when I make an HTTP request shown below, I receive the following response:

在此处输入图片说明

And in FireFox the image tries to render but I get the message: 在此处输入图片说明

The image I want to display is: 在此处输入图片说明

Anyone have any ideas?

Thanks!

So, @rkosegi's comment about downloading the file from curl helped me figure out what the issue was. Apparently I was constructing my response body incorrectly. What happened was that there was a new line inserted before the body content after my HTTP entity headers. After removing this extra newline before streaming the body content, I was able to have the browser interpreted the data correctly.

D'oh!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM