Sergey, perhaps, was right that the data is lost inside the buffer, but I am not sure of its explanation. (BufferedReaders usually do not store data inside their buffers. Perhaps he is thinking of a problem with BufferedWriters that could lose data if the main thread shuts down prematurely.) [Do not pay attention; I answered incorrectly. The rest of this is valid AFAIK.]
I think you have a problem specific to your application. In the client code, you start reading as follows:
public static void recv(Socket socket){ try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
... and you will start using in to start the exchange. But then you switch to using the raw socket stream:
while(bytesRead > fileSize){ read = socket.getInputStream().read(buffer);
Since in is a BufferedReader, it already fills its buffer up to 8192 bytes from the socket input stream. Any bytes that are in this buffer and which you do not read from in will be lost. Your application hangs because it believes that the server is holding onto some bytes, but the server does not have them.
The solution is not to make byte bytes from the socket (ouch! Your bad CPU!), But to use BufferedReader sequentially. Or, to use buffering with binary data, change the BufferedReader to a BufferedInputStream that wraps an InputStream socket.
By the way, TCP is not as reliable as many people believe. For example, when a server socket is closed, it can write data to the socket, which is then lost when the socket connection is disconnected. Calling Socket.setSoLinger can help prevent this problem.
EDIT: Also, BTW, you play with fire, processing byte and character data, as if they were interchangeable, as you do below. If the data is really binary, then converting to String can lead to data corruption. Perhaps you want to write in a BufferedOutputStream?
// Java is retarded and reading and writing operate with // fundamentally different types. So we write a String of // binary data. fileWriter.write(new String(buffer)); bytesRead += read;
EDIT 2 : Refined (or tried to clarify: -} processing binary and string data.