• Post Reply Bookmark Topic Watch Topic
  • New Topic

Stream corruption in Client server environment

 
Volker Schreiber
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
in a client server connection with sockets, I tried to send a
file from client to server. The file contains serialized objects.
It is written to the clients outputstream with
BufferedOutputStream out2 = new BufferedOutputStream(outputStream);
FileInputStream fi = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fi);
try {
int bytesRead;
while (true) {
bytesRead = in.read();
if (bytesRead == -1) break;
out2.write(bytesRead);
}
out2.flush();
} catch (IOException e) {
e.printStackTrace();
}
On the server side I tried to read the stream the following way
in = socket.getInputStream();
File temp = File.createTempFile("temp", ".bin");
FileOutputStream fileOut = new FileOutputStream(temp);
try {
byte[] input = new byte[64];
while (true) {
int bytesRead = in.read(input);
if (bytesRead == -1) {
fileOut.flush();
break;
} else if (bytesRead > 1) { // <-- the strange part!!
fileOut.write(input, 0, bytesRead); //
fileOut.flush(); //
} //
}
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
Now, as marked in the snippet, if the in.read(input) return 1, the
input still seems to be the old one (nothing new was read in). If
I don't check for bytesRead > 1, but simply write to the file stream,
it happens, that I can not read/deserialize the file content lateron
with an ObjectInputStream (however, the input stream from the client
seems to be alright). It looks like the in.read() should return 0
instead
of 1, but it doesn't. If I check with in.available() it return 0 in most
of the cases where in.read(input) return 1.
What have I done wrong? I would really like to get rid of the "strange"
part, because it might happen, that for slow network connections, the
read methode really returns 1 and the buffer is only filled with one
byte.
Sorry for the long post
Volker
 
ersin eser
Ranch Hand
Posts: 1072
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Volker
Please read the Javaranch Naming Policy and change your publicly displayed name to comply with our unique rule. Thank you for your cooperation.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!