R. Völker R. Völker - 2 months ago 10
Java Question

Strange behaviour of InputStream / OutputStream in Socket

As always I'm having trouble with Streams and Sockets.

Here is my Code:

Client

bitOut.write((f.getName() + "\n").getBytes());
//System.out.println(f.length()); // <- This is the odd part.
bitOut.write((int) f.length());
bitOut.flush();

fileIn = new FileInputStream(f);
byte buffer[] = new byte[BUFFER_SIZE];
int len;
while ((len = fileIn.read(buffer)) != -1) {
bitOut.write(buffer, 0, len);
}
fileIn.close();


Server

file = sc.nextLine();
int fileSize = bitIn.read(); // <- Here is my error!
System.out.println(file + ", " + fileSize);

fileOut = new FileOutputStream(folder + file);
byte buffer[] = new byte[BUFFER_SIZE];
int len;
while (fileSize > 0 && (len = bitIn.read(buffer)) != -1) {
fileOut.write(buffer, 0, len);
fileSize -= len;
System.out.println(fileSize);
}
fileOut.close();


If I uncomment the
System.out.println(f.length())
in the client code, the server is always getting the right value in
fileSize
. But if I leave it commented,
fileSize
is often a byte from the data which should be sent after
f.length()
. On the one hand it's funny because almost only if I print out the file size in the client, I receive the right result on the server. On the other hand I got no clue how to fix it...

Answer

Ok I solved it. It was something with the Scanner, whose method nextLine() swallowed the byte I was sending after the file name. Now I'm just using the normal InputStream and OutputStream.