Berkay Aras
Berkay Aras

Reputation: 127

Killing a thread after socket closed

I wanna kill the TCP connection listener thread(serverside) after client closes the socket.. The thread waits in the loop in the readLine().. How can i do it?

while(isconnected){
String msg = in.readLine();
//..
}

Upvotes: 2

Views: 2945

Answers (5)

Stephen C
Stephen C

Reputation: 718698

WalterM is basically right. The readLine call will return null is the stream is closed by the remote client, and will throw an exception if the connection "breaks" without a proper close, or the low-level socket read times out.

It is worth pointing out that it is simpler and more efficient to just do this:

try {
    String msg;
    while ((msg = in.readLine()) != null) {
        // do stuff
    }
} catch (IOException ex)
    // report error
} finally {
    // Close the socket under all circumstances to avoid potential
    // resource leakage
    try {
        socket.close();
    } catch (IOException ex) {
        // ignore
    }
}

Checking that the socket is still connected it redundant. The low-level socket read will be doing that anyway.

Upvotes: 0

toto2
toto2

Reputation: 5326

First, you can't tell if the client is just taking a long time to respond, or if it is down.

What you can do is set some timeout period and have a thread in the server that calls clientSocket.close() after the timeout has elapsed. This will throw a SocketException in the receiving thread. It will take you out of the receiving loop and the thread will just terminate by itself if there is nothing after the receiving loop.

Upvotes: 0

WalterM
WalterM

Reputation: 2706

You have to call socket.close() method, if you are using it properly it should be fine. I don't know where readLine() is coming from, so I will assume its BufferedReader. If you look here in the documentation BufferedReader readLine()

you will see that it throws IOException if there is an error and if it is end of stream it will return null.

so you should basically do this:

try{
  while(socket.isConnected()){
    String line = in.readLine();
    if(line==null){
      //END OF STREAM
    }
  }
}catch(IOException e){
  //deal with IOException here
}

otherwise, what I assume your currently doing is sitting in a tight loop as soon as the other end disconnects. If you try too print out msg in your above code you will see it print out null nonstop.

Upvotes: 3

Highland Mark
Highland Mark

Reputation: 1010

Perhaps extend your protocol so that the client sends a QUIT message before closing its socket.

Upvotes: 1

JohnnyK
JohnnyK

Reputation: 1102

You'll need to interrupt the thread.

Upvotes: -1

Related Questions