i have problem while sending files to my server. The main problem is the protocol. First im sending with an PrintWriter the file Size, and than im using a DataOutputStream to write the binary data to my server. Everything works fine, but there is one problem. Im using the method File.length() to get the file length. The Docs say, that its possible to read less bytes-length as the method return. And thats what happening sometimes. So after this, the while loop in my server which is reading data will never exit, because it waiting for the last bytes of data. I tried everything, like readfully() on client side. Nothing worked. Have anyone a idea how to stop this while loop in an other way? Like waiting for specific byte that tells the Server to stop it, because there is no more data to read? I dont really know how to implement a communication protocol.I searched everywhere for information but i found nothing that helped.
Why i dont closing the connection to exit the while loop? I need to use this connection later, to tell the client that the file was uploaded succesfully.
Client: Sending file length = 1000
Server: Reading file length
Client: Sending byte data ...
Server: Reading byte data ...
Client: Finished sending byte data, written only 900
Server: Still waiting for data, because it dont reached the excepted length.
private boolean uploadPicture(File file) throws Exception
{
int maxLength = Integer.parseInt(this.readDataCarefully(10)); //read until \n appears
int readed = 0;
if(maxLength >= 500000)
{
return false;
}
DataInputStream dateiInputStream = null;
FileOutputStream dateiStream = null;
dateiInputStream = new DataInputStream(this.socket.getInputStream());
dateiStream = new FileOutputStream(file);
int count;
byte[] buffer = new byte[maxLength];
while ((count = dateiInputStream.read(buffer)) > 0)
{
dateiStream.write(buffer, 0, count);
readed = readed+count;
if(maxLength <= readed) //True when file transfere complete.
{
break;
}
}
System.out.println("Finished");
dateiStream.close();
if(this.checkImageFile(file)) //Checks file
{
System.out.println("PB WRITTEN.");
return true;
}
return false;
}