Java - Read file from Socket (while loop never ends)
<p>My JAVA application sends a command to server <em>(command=filename.ini)</em>. When the server receives this command it sends filename.ini contents through Socket. 
The first problem I had was receiving only partial contents of the file. That happened when in the code I used <code>while(in.available()!=0){//write bytes}</code> because <code>in.available()</code> does not know how big/long the content of the file is. If I use <code>while((numBytesRead = dis.read(buffer)) != -1){//write bytes}</code> the loop will never terminate since the Socket connection remains always open. My question is <em>how else can I terminate the loop once every byte has been received?</em> Please help me I have tried everything. I understand where the mistake is but I don't know how to fix it.</p>

<p>The following is the part of the code I have at the moment:</p>

<pre><code>public class TCPClient {

    protected Socket s = null;
    public DataInputStream in = null;

    public TCPClient(InetAddress ipa, int port) {

        Socket s1 = null;

        try { //Open the socket.
            s1 = new Socket(ipa.getHostAddress(), port);
        } catch (IOException ex) {
            System.out.println("Error opening socket!");
            return;
        }

        s = s1;

        try { //Create an input stream.
            in = new DataInputStream(new BufferedInputStream(s.getInputStream()));
        } catch (Exception ex) {
            System.out.println("Error creating input stream!");
        }
    }

    public synchronized byte[] receive() {

        byte[] buffer = new byte[0];

        ByteArrayOutputStream getBytes = new ByteArrayOutputStream();

        try {
            while (in.available() == 0) {
            }  //Wait for data.
        } catch (IOException ex) {
        }

        try {

            int numBytesRead;
            buffer = new byte[1024];

            while ((numBytesRead = dis.read(buffer, 0, 1024)) != -1) { //LOOP NEVER ENDS HERE BECAUSE CONNECTION IS ALWAYS OPEN
                getBytes.write(buffer, 0, numBytesRead);
            }


        } catch (IOException ex) {
        }

        return (getBytes.toByteArray());
    }
}
</code></pre>
