34

I have an android app that talks to a program on a PC. I'm using the Android (Java) Socket class. If I stop and restart the PC app the next time I send something from Android I get an IO Exception "Broken Pipe". My question is not about that. Here's the question:

After getting the broken pipe exception if I query the Socket's isClosed() method it returns false (i.e., it's not closed), and if I query the Socket's isConnected() method it returns true, i.e., that it IS connected. Could someone please explain these results to me? Thanks in advance!

user316117
  • 7,971
  • 20
  • 83
  • 158
  • http://stackoverflow.com/a/3751722/776244 – Samir Mangroliya Jun 05 '12 at 14:46
  • Samir, that link is about what a broken pipe exception means. I already understand that; that's why I said my question is not about that. I want to understand the return values I'm getting from the two Socket methods. I've updated the title to clarify this. – user316117 Jun 05 '12 at 14:50

3 Answers3

26

Broken pipe means pretty much exactly what you're talking about here. The program on your side still has its socket wide open, but the socket on the other side is no longer in communication, and didn't go through the standard "close pipe" procedure. This can happen if the other side lost power suddenly, if the physical line was severed, or whatever. As such, locally the socket is registering as both open and connected - it's just connected to a broken pipe. Did you wish some practical advice here, or just the theory?

Ben Barden
  • 2,001
  • 2
  • 20
  • 28
  • I wanted to understand the Socket's response to find out if there is something I can query of the socket to know when I've lost my communication channel and those seemed like to two most likely methods. So does this mean that when the pipe breaks the first clue I'll have is landing in the "catch" portion of the "try - catch" block when I send something? – user316117 Jun 05 '12 at 14:59
  • pretty much. The whole point of a broken pipe is that it's not anything that happened locally, and your system wasn't informed it was happening when it happened. – Ben Barden Jun 05 '12 at 15:19
5

Socket.isClosed() and Socket.isConnected() only tell you what you have done to the socket. They aren't there to tell you anything about the state of the connection. You haven't closed the socket: it's open. You connected the socket: it's connected.

When you get any IOException operating a Socket other than SocketTimeoutException you must close the socket.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

I got same problem when I was trying to send data from my Android App to a bluetooth module attached to an Arduino, and it it took me too long until I changed the bluetooth module with a new one and everything start working perfectly, so it is also worth checking your hardware, specially if you are confident about your code and running out of solutions.

omzer
  • 1,200
  • 11
  • 14