怎样让socket接收端通过已知文件长度来接收文件
怎样实现让接收端通过已知文件长度来接收文件。发送端和接收端具体的实现方法?
原来我在文件传输过程中没有涉及文件长度,发送端发送完后,关了输出流,就自动关闭了Socket,无法继续发送其它文件。通过搜索相关问题答案,我考虑通过文件长度来传文件。
下面是我的部份代码:
----------------------------------------------------
发送方:
Socket socket_send;//已连接了对方
OutputStream ops = socket.getOutputStream();
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream("待发送文件")));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(ops));
byte[] buf = new byte[1024];
while((dis.read(buf))!=-1)
{
dos.write(buf,0,buf.length);
}
dos.flush();
dos.close();//如果没有这句,接收方while((dis.read(buf))!=-1)将一直等待,就连文件数据传完了也不会退出while语句.但加了这句,就可以正确地发送该文件了,只不过发完后,socket也断开了,不能再重复发文件了......
---------------------------------------------------
接收方:
Socket socket_accept;//已连接了对方
InputStream ips=socket_accept.getInputStream();
BufferedInputStream br=new BufferedInputStream(ips);
DataInputStream dis= new DataInputStream(br);
DataOutputStream dos= new DataOutputStream(new BufferedOutputStream(new FileOutputStream("保存目录")));
byte[] buf = new byte[1024];
while((dis.read(buf))!=-1)//如果发送方没关闭输出流,则不会退出循环
{
dos.write(buf,0,buf.length);
}
dos.flush();
dos.close();