I’m just now learning how to use the Android/Java Socket class and I need to respond in a particular way to a Close (FIN, really) sent by the remote computer.
The Socket class does not seem to be event-driven (http://developer.android.com/reference/java/net/Socket.html) i.e., there don’t seem to be any onThis or onThat handlers, so what’s the best way to become aware of when the remote computer sends a FIN?
Currently the Android OS responds to the FIN with an ACK, but I need to do things in my application as well so I need a way for my app to be alerted to this.
Thanks in advance!
You, as an application programmer, rarely if ever need to even care about FINs and ACKs. They’re built into the TCP/IP stack, and the OS will take care of all that for you. You’re going too low-level for your own good; if you really want to mess with that stuff, then you won’t be able to use
Socket— you’d need to get into raw sockets and such, which is way more work than you’re ready for. (I’m not sure if Java or Android would even let you do it.)As for detecting the other end closing its side of the connection (which is basically what a FIN is), just read from the socket. If the other end has shut down its sending side, a read will read 0 bytes (or return
-1, depending on whether you’re trying to read a bunch of bytes or just one).