我正在尝试在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);
}
答案 0 :(得分:0)
传输二进制数据时,你不应该解析检查新行等的内容,你的图片还包含这些\ n r字符