I want to send multiple files with a socket connection. For one file it works perfectly, but if I try to send more than one (one at a time) I get a Socket Exception
:
java.net.SocketException: socket closed
In general, my connection works like this:
- Server waits for connection
- Client connects to the server and sends a request for a certain file (string that contains the filename)
- Server reads the local file and sends it to the client
- Client sends another request for another file and continues at point 3.
The run-Method for the waiting-for-request-procedure looks like this:
@Override
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
if (message.equals(REQUESTKEY)) {
System.out.println("read files from directory and send back");
sendStringToClient(createCodedDirContent(getFilesInDir(new File(DIR))), socket);
} else if (message.startsWith(FILE_PREFIX)) {
String filename = message.substring(FILE_PREFIX.length());
try {
sendFile(new File(DIR + filename));
} catch (IOException e) {
System.err.println("Error: Could not send File");
e.printStackTrace();
}
} else {
System.out.println("Key unknown!");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
and my sendFile()
Method looks like this:
public void sendFile(File file) throws IOException {
FileInputStream input = new FileInputStream(file);
OutputStream socketOut = socket.getOutputStream();
System.out.println(file.getAbsolutePath());
int read = 0;
while ((read = input.read()) != -1) {
socketOut.write(read);
}
socketOut.flush();
System.out.println("File successfully sent!");
input.close();
socketOut.close();
}
I think the problem lies in the socketOut.close()
. Unfortunately, the method closes the socket connection too (problem for further connections). But if I leave out this closing the file-transfer doesn't work correctly: files arrive incomplete at the client.
How can I avoid or fix this problem? Or is there even a better way to transfer multiple requested files?
Thank you