Kasonge Mabunoa
Kasonge Mabunoa

Reputation: 3

Sending and creating a File

I'm writing a custom protocol. I have a command name's put and the code looks as follows.

if(commandString.equals("PUT")){
    File f = new File(currentFolder, "test.txt");
    if(!f.exists())
         f.createNewFile();
    FileOutputStream fout = new FileOutputStream(f);
    long size = 150;
    long count = 0;
    int bufferLeng = 0;
    byte[] buffer = new byte[512];
    while((bufferLeng = dis.read(buffer))>0) //dis is a data input stream.
    {
        count =+ bufferLeng;
        fout.write(buffer);
    }
    System.out.println("All Good");
    fout.flush();
    fout.close();

}

This command gets sent to the server by the client as follows pWriter.println("PUT");. Now I run this and it does create the file test.txt but then is freezes and the server does not display the All Good message. Why would this be and what is a easy fix?

The server and the client works!!

Thank you

Upvotes: 0

Views: 58

Answers (2)

Jonathan
Jonathan

Reputation: 535

Perhaps eliminate dis.read(buffer) and use the following.

if(commandString.equals("PUT")){
    File f = new File(currentFolder, "test.txt");
    if(!f.exists())
         f.createNewFile();
    FileOutputStream fout = new FileOutputStream(f);
    long size = 150;
    long count = 0;

    byte[] buffer = new byte[512];
    int bufferLeng = buffer.length;
    while(count < size && bufferLeng>0) //dis is a data input stream.
    {

        fout.write(buffer);
        count =+ bufferLeng;
    }
    System.out.println("All Good");
    fout.flush();
    fout.close();

}

This should work

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328770

The server waits for the client to close the socket. This would transmit the end-of-file which would cause dis.read() to return -1.

Usually, this isn't what you want. The solution is to send the file size before the data and then read exactly this amount of data.

Make sure your client calls socket.flush() after writing the last byte of file data or the data might get stuck in a buffer which would also cause the server to hang.

Upvotes: 1

Related Questions