Bimp Bimp - 11 months ago 71
Java Question

Java socket exception: recv failed

This is basically the picture:
I have a server and a client (operating through localhost). Server creates a clientthread for each connection. this new thread blocks on read waiting for messages from client. At will, i can deactivate the server through the GUI, which sends (from a main thread) "disconnect" to the client, and then closes the output stream, to wake up the blocked clientthread, which in turn finishes up by closing the socket (I believe this closing is unnecessary after closing outputstream but anyway).

Client side:
After connection request, it sleeps 10 seconds, writes a disconnect message and reads the answer char by char.

The problem:

After deactivating the server within that 10 second client sleep time, client reads the "disconnect" message correctly from the server. However, If I just add a dummy print for each char read (inside the while loop), the result of the final read is varying.
Sometimes it will read the server's "disconnect" correctly, sometimes it will read "disco", or a similar variation, and throw this exception:

"Java exception : "Software caused connection abort: recv failed"

Any suggestions as to why adding a few prints creates this result? I would assume having a closed socket on the other end wouldn't have an effect on reading the message.
The other threads I found about recv errors mentioned timeouts, which I'm guessing shouldn't really be happening when using localhost?

Answer Source

The error occurs because the other end has disconnected and your write has failed. If you read quickly enough, it hasn't determined the connection has been lost.

There are ways to avoid this error, but the simplest thing to do is to ignore it