J. Doe
J. Doe

Reputation: 1549

Can't get my java server to accept a file transfer from my client

I have two files: a chat server and a chat client. The chat client is supposed to say that it wants to upload a file to the server. And then it uploads. However, right now, all of the messages are being sent / received properly, but when I try to get the file transfer, the only thing I get is a file with 0 bytes (which is at the path I specify inside of the server class.

Broken part of the chatclient class:

/**
 * Sends a broadcast to the server
 */
public static void broadcast() throws IOException {

    if (UserInput.getText() == "/upload") {

        File myFile = new File (FILE_TO_SEND);
        byte [] mybytearray  = new byte [(int)myFile.length()];
        fis = new FileInputStream(myFile);
        bis = new BufferedInputStream(fis);
        bis.read(mybytearray,0,mybytearray.length);
        os = Socket.getOutputStream();
        System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
        os.write(mybytearray,0,mybytearray.length);
        os.flush();
        System.out.println("Done.");
    }

    System.out.println("" + UserInput.getText());

    outputStream.println(UserInput.getText());
    outputStream.flush();
}

Broken part of the server class:

if (input.contains("/upload")) {
    byte [] mybytearray  = new byte [FILE_SIZE];
    InputStream is = csocket.getInputStream();
    fos = new FileOutputStream(FILE_TO_RECEIVED);
    bos = new BufferedOutputStream(fos);
    bytesRead = is.read(mybytearray,0,mybytearray.length);
    current = bytesRead;

    do {
        bytesRead =  is.read(mybytearray, current, (mybytearray.length-current));
        if (bytesRead >= 0) current += bytesRead;
    } 
    while(bytesRead > -1);

    bos.write(mybytearray, 0 , current);
    bos.flush();
    System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)");
}

Upvotes: 0

Views: 218

Answers (2)

user207421
user207421

Reputation: 311050

Your copy loop is nonsense. The canonical way to copy a stream in Java is as follows:

while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

where 'count' is an int, and 'buffer' is a byte[] array of length > 0. I usually use 8192.

Upvotes: 1

agg.ie
agg.ie

Reputation: 11

You should try surrounding the broken code with try-catch block and print out the error message from the stack. this would give you a better idea of what is not working. It's not a solution, I know, but it's easier to find a solution if you know the exact problem.

Upvotes: 0

Related Questions