如何通过Java在套接字上发送文件列表 [英] How to send a list of files over a socket in Java
问题描述
我已使用代码此处通过套接字发送单个文件。但是,我需要能够通过套接字发送多个文件(基本上是目录中的所有文件),并让客户端识别文件之间的分离方式。坦率地说,我完全不知道该做什么。任何提示都会有所帮助。
I have used the code here to send an individual file over a socket. However, I need to be able to send multiple files (basically all files in a directory) over the socket and have the client recognize how the separation between files. Frankly, I am at a complete loss for what to do. Any tips would be helpful.
注意1:我需要一种方法在一个连续的流中发送文件,客户端可以将这些文件分隔成个人文件。它不能依赖客户的个别请求。
NOTE 1: I need a way to send the files in one continuous stream that the client can segregate into individual files. It cannot rely on individual requests from the client.
注意2:要回答一个问题,我很确定我会在评论中加入,不,这是 NOT 作业。
NOTE 2: To answer a question I am pretty sure I will get in the comments, no, this is NOT homework.
编辑有人建议我可以发送文件的大小在文件本身之前。我怎么能这样做,因为通过套接字发送文件总是以预定的字节数组或单个字节完成,而不是由 File.length()$返回的long。 c $ c>
EDIT it has been suggested that I could send the size of the file before the file itself. How can I do this, as sending a file over the socket is always done in either a predetermined array of bytes, or a single byte individually, rather than the long returned by File.length()
推荐答案
以下是完整实施:
发件人方:
String directory = ...;
String hostDomain = ...;
int port = ...;
File[] files = new File(directory).listFiles();
Socket socket = new Socket(InetAddress.getByName(hostDomain), port);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(files.length);
for(File file : files)
{
long length = file.length();
dos.writeLong(length);
String name = file.getName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte = 0;
while((theByte = bis.read()) != -1) bos.write(theByte);
bis.close();
}
dos.close();
接收方:
String dirPath = ...;
ServerSocket serverSocket = ...;
Socket socket = serverSocket.accept();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
long fileLength = dis.readLong();
String fileName = dis.readUTF();
files[i] = new File(dirPath + "/" + fileName);
FileOutputStream fos = new FileOutputStream(files[i]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for(int j = 0; j < fileLength; j++) bos.write(bis.read());
bos.close();
}
dis.close();
我没有测试它,但我希望它能运作!
I did not test it, but I hope it will work!
这篇关于如何通过Java在套接字上发送文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!