Question

I am trying to write a server that accepts files and write it in certain directory using DataInputStream and BufferedInputStream.

The server gets 'user name(string)' 'number of files(int)' 'file name(string)' 'size of each file(long)' and 'contents of file which is uninterpreted bytes(byte[])'

and if everything is successful then, I am supposed to send boolean value.

But the problem is that it is not receiving file correctly.

From time to time I get 'broken pipe' error message or the file is corrupted after I receive.

I looked at my code for 4hrs and couldn't find the problem.

Would you please help me about this? You can assume that client is working fine.

Was it helpful?

Solution

FIrst you don't have to close all of those streams. That's probably why you're seeing the broken pipe problem. You just need to close the input and output stream.

DataInputStream din = new DataInputStream( new BufferedInputStream( socket.getInputStream() ) );
DataOutputStream dout = new DateOutputStream( new BufferedOutputStream( socket.getOutputStream() );
try {


} finally {
   din.close();
   dout.close();
}

The reason you don't have to close all of those streams is because your Buffered*Streams and socket InputStream/OutStream will be closed when din/dout.close() is called. Those will close the streams through the reference they chain to. You can also get rid of all that if( blah != null ) junk on each of those because if you make it to the finally clause you know they are non-null. You know that's the case if you don't new up inside the try.

You're also leaking your FileOutputStream because you overwrote the fos variable with the second new FileOutputStream(). What are you doing there with the SUBMIT_DONE file? That's truly weird. It's pretty bad idea to do that. Don't use variable references twice like that. I would probably close the first file after your loop. Think about wrapping that loop with try {} finally { fos.close(); }.

And you might try using methods to break this up a little. Ditch the static.

Update:

What exactly do you think the following is doing?

while(c!='\0') {
   userName += c;
   c = din.readChar();
}

Depending on how you are sending the data from your client or server you could just use:

String userName = din.readUTF();

Remember with DataInputStream you are processing formatted BINARY data. You also have that exact loop code repeated again for the filenames. If you can't use readUTF() then create a method that wraps up that loop and returns a string and call it from those two places. You have all sorts of security issues allowing clients to upload raw filenames and files to you. I hope to sweet baby jeez this server you're building isn't being deployed in production.

You also need to flush and close each file you receive over the socket so the full amount of data sent is completely written to the files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top