File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes Read, Send, Write a File through a socket Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Read, Send, Write a File through a socket" Watch "Read, Send, Write a File through a socket" New topic

Read, Send, Write a File through a socket

Jae Lee

Joined: Jun 10, 2011
Posts: 5
Hi. I am trying to send a file "Props.txt" from a client to a server using a Socket.
I am currently receiving and error from the server side stating that there is a "Connection Reset".

I am wondering what I am doing wrong.



thank you in advance for the help.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

There are numerous things wrong with that.

First of all the protocol is a mess. Don't mix text with bytes, for one thing. Use a DataOutputStream to send the size of the file as a long value (not an int, that isn't big enough) and a DataInputStream to receive it. Avoid the use of Writers and Readers unless your protocol is entirely text.

And you might be losing data by opening more than one buffered input over the same input stream: the first one may buffer data which you then ignore when you start using the second one. You don't want to ignore data like that.

And don't use a PrintWriter: it doesn't tell you about errors (read its documentation to find out about that). In network communications you do want to be told about errors when they occur.

And your code for reading the data from the socket to the file is wrong. You read chunks of data from the socket until the length of a chunk is equal to the total number of bytes you expect to get. This might just happen to work for a small file, if you get it all at once, but for a larger file it's just going to hang when you get to the end of the stream. Change it to count the received bytes properly.
Jae Lee

Joined: Jun 10, 2011
Posts: 5
thank you for your input.
i wish my professor went over this before hand.
after reading up on the topics, i seem to have a better grasp of things.
thanks for you help. i really appreciate it.

I agree. Here's the link:
subject: Read, Send, Write a File through a socket
It's not a secret anymore!