2017-03-08 43 views
2

我有这个简单的HTML,当我在Chrome中加载它时加载了我想要的。当通过套接字java发送HTML页面时不会加载图像

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

当我通过Java中的套接字传递它时,我总是得到一个破损的图像。我无法弄清楚为什么,因为我只是通过套接字传递字节。

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

图像文件“cat.jpg”与“index.html”位于同一个目录中。我错过了什么?

回答

0

我认为问题在于它发送另一个http请求。你应该提供例如:127.0.0.1/index.html来显示你的index.html文件,而127.0.0.1/cat.jpg应该返回你的照片。 但我不确定你将如何解析java中的jpg文件。 但是,如果你在铬,你去检查;你去网络。从那里如果你重新加载,你会看到一个请求你的图片或者正在等待,或者不是你返回的正确信息,这取决于你如何实现我们对http请求的处理。