Search code examples
javaandroidsocketsserversocket

Detect when a client is no longer listening to server


I am writing an application that streams data that clients can then listen to and receive. However I am running into an issue with closing a socket when a client is no longer listening.

What I do is create a ServerSocket, when then waits for a connection and once it is connected, I start streaming the data. However, once the client is no longer connected, I am stuck in a loop of streaming and cannot tell if anyone is listening. Is there a way around this?

try {
    serverSocket = new ServerSocket(STREAM_PORT);
    Socket clientSocket = serverSocket.accept();
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(), true);

    while (true) {
        pw.println("some data");
    }
} catch (SocketException e) {
    // Never occurs when client disconnects
} catch (IOException e) {
    // Never occurs when client disconnects
}

I have tried using socket.isClosed(), but it always returns false. Am I approaching this from the wrong angle, or is there a way to do it. I would ideally not want the client to have to send the server a "end" command.

EDIT: Edited to reflect what current code I am running after @Rod_Algonquin suggestion


Solution

  • As you are using PrintWriter, which swallows I/O exceptions, you need to call checkError() after each write to see if an error has occurred.