0

I have a problem with sockets in Java. I have implemented Server and Client to communicate and send files from client to server. The problem is that sometimes method in.read(buffer) gives me -1 instead of the real file length. It occurs nearly randomly.

Servers part:

InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream(file);
System.out.println("Server: Will receive file...");
byte[] buffer = new byte[4096];
int length = in.read(buffer);
System.out.println("Server: will get " + length + " byte");

while (length > 0){
    out.write(buffer, 0, length);
    System.out.println("Server: reading !");
    length = in.read(buffer);
}

System.out.println("Server: got file, length: " + file.length());

in_code.close();
out.close();
in.close();

Client:

public void sendFileToServer(String s) throws IOException{
    try{
        clientSocket = new Socket(ip, port);
    }catch (Exception e){
        e.printStackTrace();
    }

    File file = new File(s);
    String filename = file.getName();
    this.sendCode(filename);

    // Get the size of the file
    long length = file.length();

    System.out.println("Client: send file name: " +filename);
    System.out.println("Client: send file length: " +length);

    byte[] bytes = new byte[1024];
    InputStream in = new FileInputStream(file);
    OutputStream out = clientSocket.getOutputStream();
    int count;

    while ((count = in.read(bytes)) > 0) {
        System.out.println("Client send !!!");
        out.write(bytes, 0, count);
    }

    out.close();
    in.close();
    this.clientSocket.close();
}

The server part is in while loop of course. Can't paste all because its a lot of code.

So the client is calling the sendFileToServer() method - let's say 5 times. One by another in a loop. And sometimes server gets all files correct, sometimes some of the files are 0, because in.read(buffer) gives -1. But on the other hand in.read() in client is correct.

Why does this happen?

mike
  • 4,929
  • 4
  • 40
  • 80

1 Answers1

0

The documentation of InputStream#read(byte[]) states:

[the method returns] the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

So if the method returns -1, it's not a network error. It is standard behavior that indicates that the Socket or Input/OutputStream has been closed.

I don't know your whole server code, but it seems that you are trying to reuse a previously closed socket on the server side.

mike
  • 4,929
  • 4
  • 40
  • 80
  • I agree that his design is flawed, but `sendFileToServer` creates a new Socket everytime. I suppose, since he also said that the client code does not yield `-1`, the accepting of clients on the server side has faulty code. – mike Nov 22 '16 at 18:57