简体   繁体   English

如何在Java中通过套接字传输文件信息和多个文件?

[英]How to transfer file info and multiple files over a socket in Java?

I have one client and one server communicating with each other via TCP sockets. 我有一个客户端和一台服务器通过TCP套接字相互通信。 The client would like to transfer two files and some description of the files to the server. 客户端希望将两个文件和一些文件描述传输到服务器。 I would like to design a protocol that once a socket is established between the client and the server, the server would expect to receive the file description first and then the two files. 我想设计一种协议,一旦在客户端和服务器之间建立套接字,服务器将期望首先接收文件描述,然后再接收两个文件。 Currently, with the following code, the server can receive the description but fails to distinguish the two files (the two files transferred from the client are merged into one single file at the server). 当前,使用以下代码,服务器可以接收描述,但是无法区分两个文件(从客户端传输的两个文件在服务器上合并为一个文件)。 I found similar threads on this issue. 我在这个问题上发现了类似的话题。 But they separately discussed "file info + one single file" and "multiple file without pre-file-info". 但是他们分别讨论了“文件信息+一个文件”和“没有预文件信息的多个文件”。 Please give me a hint on resolving this issue. 请给我有关解决此问题的提示。 Many thanks. 非常感谢。

Sever-side code 服务器端代码

dis = new DataInputStream(clientSocket.getInputStream());
callInfo = dis.readUTF();
callInfos = callInfo.split(" ");

FileOutputStream fos = new FileOutputStream(File1);
byte[] buffer = new byte[clientSocket.getReceiveBufferSize()];
int bytesReceived = 0;
while ((bytesReceived = dis.read(buffer)) > 0)
    fos.write(buffer, 0, bytesReceived);
fos.flush();
fos.close();

fos = new FileOutputStream(File2);
while ((bytesReceived = dis.read(buffer)) > 0)
    fos.write(buffer, 0, bytesReceived);
fos.flush();
fos.close();

Client-side code 客户端代码

String fileIno = "fileIno";
byte[] buffer = new byte[socket.getSendBufferSize()];
int bytesRead = 0;
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(fileInfo);

FileInputStream file = new FileInputStream(File1);
while ((bytesRead = file.read(buffer)) > 0)
    dos.write(buffer, 0, bytesRead);
dos.flush();
file.close();

file = new FileInputStream(File2);
while ((bytesRead = file.read(buffer)) > 0)
    dos.write(buffer, 0, bytesRead);
dos.flush();
file.close();

Design your protocol such that the "file description" information includes the number of bytes in each file. 设计协议,使“文件描述”信息包括每个文件中的字节数。 Then you will know where the first file begins and ends and where the second file begins and ends. 然后,您将知道第一个文件的开始和结束位置,以及第二个文件的开始和结束位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM