简体   繁体   中英

HTML page won't load image when sent through socket java

I have this simple HTML that loads how I want when I load it in Chrome.

<body>
    <div><h1>Welcome to my webpage!</h1></div>
    <div>This page is being hosted on the local machine.</div>
    <div>Now, here's a picture of a cat. Please enjoy.</div>
    <img src="cat.jpg" alt="Business Cat" width="800" height="600"/>
</body>

When I pass it through a socket in Java, I always get a broken image. I can't figure out why, because I'm just passing bytes through the socket.

File index = new File("index.html");

byte[] bytes = new byte[16 * 1024];

InputStream in = new FileInputStream(index);

while (true)
{
    int read = in.read(bytes);
    if (read < 0)
         break;
    out.write(bytes, 0, read);
}

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

The image file "cat.jpg" is in the same directory as "index.html". What am I missing?

I believe the problem is with the fact that it sends another http request. You should make provision for example: 127.0.0.1/index.html to display your index.html file while 127.0.0.1/cat.jpg should return your picture. I am not sure however how you would parse a jpg file in java. But if you are in chrome and you go to inspect; and you go to network. From there if you reload, you will see a request for your picture is either pending, or not the correct information that you returned, depending on how you implemented our handling of http requests.

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