我正在尝试在 java 上编写服务器端和客户端。因此,客户端发送请求,如 GET / HTTP/1.0,服务器端响应(如果文件存在),如 HTTP/1.0 200 OK,输入标头内容类型和内容长度,并将来自 FileInputStream 的流写入 BufferedOuputStream。服务器端:
String endLine = "\r\n";
File f = new File(fileName);
FileInputStream fstream;
fstream = new FileInputStream(f);
response = "HTTP/1.0 200 OK" + endLine;
header = "Content-type: "+ contentType + endLine + "Content-length: " + f.length() + endLine + endLine;
bout.write(response.getBytes());
bout.write(header.getBytes());
int lol;
while((lol = fstream.read(buffer)) != -1) {
bout.write(buffer,0,lol);
}
System.out.println("Message sent");
bout.flush();
socket.close();
客户端:
byte[] res = new byte[bufferSize];
int got;
int i=0;
int temp = 0;
int j = 0;
while((got = bis.read(res))!=-1){
for(j=0;j<res.length;j++){
//dividing from header
if(res[j]=='\n'&&res[j-1]=='\r'&&res[j-2]=='\n'&&res[j-3]=='\r'){
temp = j+1;
}
}
fout.write(res,temp,got-temp);
i++;
}
因此,使用 .html 文件可以正常工作,但使用图像...
找到了解决方案。错误出现在偏移量上:
fout.write(res,temp,got-temp);
此行在每次迭代中添加偏移量。我只需要先:
if(i==0){
fout.write(res,temp,got-temp);
}else{
fout.write(res,0,got);
}