Neither the client or the server has any idea how much data is being exchanged. And, if one disconnects before the other has read the last message, the connection will be lost causing the error you are observing.
Here's a thought on what you can do:
- Use a synchronous client/server.
- Define a message protocol:
- Have the client send a "GO" message like <GO/>.
- Wait for the server to respond with an OK message like <OK/>. This indicates that the server is about to send bytes.
- The server sends the bytes using some message like <DATA>chunk-of-data</DATA>.
- When the client receives the bytes, the client responds an OK message (<OK/>). The server waits for the client's OK message before sending the next chunk of data.
- When the server has send the last chunk of data and has received the client's OK message, the server sends a "finished" message like <FINISHED/>.
- The server waits for the client to respond with <OK/>. This indicates that the server can disconnect.
- Now you can shut down the connection on the client side.
You have very little control over the size of the buffers, so you may need to insure that two or more data buffers are properly identified in a message.
Hope that helps.