I have a java server that sends files to an android client. for some reason, the server seems to be closing the socket after only one pass through, I want it to send all files then close socket, here is my server code. Thanks in advance
public void run() {
DataOutputStream dos = null;
try {
String path = "/home/test";
int count = 0;
dos = new DataOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
DataInputStream dis = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
File[] files = new File(path).listFiles();
for (File file : files) {
String filename = file.getName();
String extension = filename.substring(
filename.lastIndexOf(".") + 1, filename.length());
if ("png".equals(extension)) {
count += 1;
}
}
System.out.println("Sending " + count + " files");
dos.writeInt(count);
dos.flush();
byte[] temp = new byte[1024];
int n = 0;
for (File file : files) {
String filename = file.getName();
String extension = filename.substring(
filename.lastIndexOf(".") + 1, filename.length());
if ("png".equals(extension)) {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte fileContent[] = new byte[(int) file.length()];
bis.read(fileContent);
int dataLength = fileContent.length;
dos.writeInt(dataLength);
dos.flush();
int open = dis.readInt();
System.out.println("still open if open = 5: open = "+open);
System.out.println(filename + " is " + dataLength
+ " bytes long");
while ((dataLength > 0)
&& (n = bis.read(temp, 0,
(int) Math.min(temp.length, dataLength))) != -1) {
dos.write(temp, 0, n);
dos.flush();
dataLength -= n;
}
System.out.println("Sent file "+filename);
fis.close();
bis.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try{
if (dos != null) {dos.close();}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Any chance your Android application is spinning? You have a logic error in your code. It reads in the whole file into
fileContentbut then you go into yourwhileloop waiting for the file to be fully read.You’ve already read in the entire file from
bisso when you are reading more you are gettingn == 0so it is looping forever.If you want to do the buffering, then you should remove the
bis.read(fileContent);. If you want to read the file at the start then you need to remove thewhileloop.