Skip to content Skip to sidebar Skip to footer

Java.net.socketexception: Sendto Failed: Epipe (broken Pipe) When Sending Character To Check Socket Connection

I develop a system include: socket server on Android Mobile and socket client on PC. And to check the connection with client, I had sent a ' ' character every 1 second from server.

Solution 1:

When an Android is kept idle, the device locks and then it goes to deep sleep mode. In deep sleep mode the Android system, closes the existing network connections like TCP or UDP. If your app is connected to a server, it loses connection to the server and tries to reconnect based on the reconnect attempt methods configured for the client. But if your app is the server, all the client will lose connection to the server, and you have to start the socket again in server and try to connect once again from the clients.

Keeping a TCP connection open for extended periods may not be a good option for a mobile device, because TCP connections don't interact well with computers that go to sleep. The problem scenario would be this: your Android user puts his Android device to sleep while your app is running, and then the remote user's program (or whatever is at the other end of the TCP connection) sends some data over the TCP stream. The remote user's program never gets any ACKs back from the Android device, because of course the Android device is asleep, so the remote device's TCP stack assumes that the TCP packets it sent must have been lost, and it responds by increasing its timeout period, decreasing its TCP window size (aka number-of-TCP-packets-allowed-in-flight-at-once), and resending the TCP packets. But the Android device is still asleep, and thus the same thing happens again. The upshot is that a few minutes later, the remote end of the TCP connection has slowed down to the point where even if the Android device was to wake up, the TCP connection will likely be too slow to be usable -- at which point your program will need to close the bogged-down TCP connection and start up a fresh one anyway, so why bother trying to keep it open?

Solution

Acquire a PARTIAL_WAKE_LOCK, and trap when the screen goes off. Then disable and reenable the wifi. This works because the filter only turns on when the screen goes off, so starting wifi with the screen off will keep it working until the screen goes off again.

Solution 2:

But sometimes, I got the exception:

java.net.SocketException: sendto failed: EPIPE (Broken pipe)

EPIPE is triggered if you write to a socket but the peer has closed the socket already. Thus this exception indicates that you can no longer communicate through this socket.

Solution 3:

Your system is working exactly as designed. You sent the heartbeat, it fails, you've detected a dead connection. That's the purpose of the code.

Post a Comment for "Java.net.socketexception: Sendto Failed: Epipe (broken Pipe) When Sending Character To Check Socket Connection"