简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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