1

I have a class in my android app that have a ServerSocket in it and a single Socket that will hold the client object when it is connected. Now what I want to do is to create a callback that would raise when client is disconnected from either side. May be something like onSocketClose(Socket socket) or may be onDisconnect(Socket socket). Is there a way I can do this?

My server(Android app) code:

private ServerSocket serverSocket;
private Socket client;

public WiFiSender() {
    try {
        serverSocket = new ServerSocket(8);
    } catch (Exception ex) {
    }
}

public void start() {
    try {
        client = serverSocket.accept();
        if(client != null){
            Toast.makeText(null,"Device Connected at "+client.getInetAddress().toString(),Toast.LENGTH_SHORT)
                    .show();
        }
    } catch (Exception ex) {
    }
//some callback to handle client's disconnection

}

I can create a separate wrapper class over this one if it helps.

Tariq
  • 2,489
  • 11
  • 36
  • 61
  • I suspect you can't actually do this without something that periodically polls, and even that is tricky. While not quite a duplicate see http://stackoverflow.com/questions/14010194/detecting-socket-disconnection and http://stefan.buettcher.org/cs/conn_closed.html – Chris Stratton Oct 02 '13 at 16:58
  • You might try Netty. It has support for exactly these types of events (`channelInactive` method of `SimpleChannelInboundHandler`, for example). – Zebby Dee Oct 02 '13 at 17:12

0 Answers0