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?