关于自定义协议利用SOCKET传输文件
首先要说明,因为我不会去关闭服务器上的流和客户端的流,因为我想让客户端利用一个socket随意传递数据,不限次数
不能关闭流,那么不能通过while判断read是否返回-1来判断文件是否传递完毕。所以我采用提前告诉客户端文件大小,来决定服务器和客户端的write和read次数,但是却造成服务器发送的文件还没发送完,客户端就已经使用完所有read次数了
为了方便大家看,我截取重要代码,下面这里是服务器发送文件的代码
private void sendFile(String filePath, BufferedWriter bw)
throws IOException {
File file = new File(filePath);
if (!file.exists()) {
return;
}
// 文件读取流
BufferedInputStream bin = new BufferedInputStream(
new FileInputStream(file));
// 发送Head
bw.write("file,"+file.length()+"\n");
bw.flush();
byte[] b = new byte[8192];
int i=0;
int sum;
while ((sum = bin.read(b)) != -1) {
out.write(b,0,sum);
System.out.println("server"+i+"====>>>"+sum+"====>"+(file.length()));
i++;
out.flush();
}
out.flush();
System.out.println("传输完毕");
bin.close();
}
}
这里是客户端接受文件代码
long count = Long.parseLong(data.split(",")[1]);
long time;
if (count % 8192 == 0)
time = count / 8192;
else
time = count / 8192 + 1;
BufferedOutputStream bout = new BufferedOutputStream(
new FileOutputStream("G:\\text.chm"));
int sz;
byte[] b = new byte[8192];
for (int i = 0; i < time; i++) {
sz = in.read(b);
bout.write(b, 0, sz);
System.out.println("client:"+i + "/" + time+"======>>"+sz);
}
System.out.println("下载完成");
bout.flush();
bout.close();