-1

I am trying to transfer an XML file in Java but the client which receives the file freezes in an infinite loop and I don't know how to solve it.


The code I am using to send the file is:

FileInputStream fileInputStream = new FileInputStream(new File("file.xml"));
byte[] buffer = new byte[socket.getSendBufferSize()];
int bytesRead = 0;
while((bytesRead = fileInputStream.read(buffer)) > 0)
{
    out.write(buffer, 0, bytesRead);
}
out.flush();
fileInputStream.close();

and the code I am using to receive the file is:

byte[] mybytearray = new byte[1024];
File file = new File("file.xml");
FileOutputStream fileOutputStream= new FileOutputStream(file);
int bytesRead = 0;
while((bytesRead = in.read(mybytearray, 0, mybytearray.length)) > 0);
{
    fileOutputStream.write(mybytearray, 0, bytesRead);
}
fileOutputStream.close();

Could you help me?

Thank you!

JohnQ
  • 1,073
  • 2
  • 10
  • 17
  • 1
    Do you close the connection/socket? – beny23 Oct 01 '12 at 22:25
  • a) not seeing anything to do with sockets here. b) what is "in" in the receiving sample? c) what about using IOUtils instead of writing this yourself? – digitaljoel Oct 01 '12 at 22:27
  • private ObjectInputStream in = = new ObjectInputStream(socket.getInputStream()); private ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); – JohnQ Oct 01 '12 at 22:28
  • I don't close the connection because it's shared between all the activities of an Android application. – JohnQ Oct 01 '12 at 22:30
  • 3
    Then your receiver will not know that the file is complete, hence it blocks and doesn't finish. If you want to keep the connection open, you'd have to send the size of your file so that the receiver knows when you're done. One thing though, I don't think it's such a good idea to just leave connections open... – beny23 Oct 01 '12 at 22:34
  • i don't see how you define in and out – amphibient Oct 02 '12 at 22:33

1 Answers1

1

The receiver does not know when the data finishes, so the receiver is blocked at reading data from socket until timeout. two solutions:

  1. send size firstly and read enough data(same as size) and then close socket of jump out reading.

  2. after finishing sending xml file, send an EOF to indicate the file finished, when reading the EOF, jump out.

Tony Zhu
  • 301
  • 1
  • 6
  • 16
  • In your application, you can make the rules. i.e. in SMTP, the \n.\n means the end of mail content. – Tony Zhu Oct 02 '12 at 22:23
  • @TonyZhu: Sending a raw XML file can make using delimiters a little difficult. There is no telling what is in the xml file. – grieve Oct 02 '12 at 22:36
  • @grieve It is second solution, if it is difficult to use delimiters, I think the first solution is proposed. – Tony Zhu Oct 02 '12 at 23:50
  • If you're sending XML it is already self-delimited. No need for yet another application protocol for EOF. – user207421 Dec 11 '16 at 00:48