I'm having problem closing a socket when the Java program is terminated (By exception or manually). I could use some help!
I'm writing a program in Java that uses TCP socket to communicate with a server. I have a socket that is used by two threads - one uses it for sending data and the other one for receiving data. My current idea to deal with the problem is closing the socket while the receiving data thread dies (i would love to hear more ideas). I didn't find any way to close the socket when the thread (the whole program) is terminated. Is there any way to call the close method when the thread is dying? (Looking for something kind of like C++'s destructor) Iv'e tried using statement and try-finally and it didn't work.
public class Receive implements Runnable {
....
....
public void run() {
Socket socket = getSocket() // Gets socket from a singleton class.
....
while (true){
....
readFromSocketFunction();
....
}
....
} // Would like to close the socket when going out from this scope.
....
}
Right now when I terminate the program, the socket keeps living. I wrote a simple client in Python and I noticed that when i interrupt the client while running, it still closes the socket (the server disconnects from the client), and I would like to have the same behavior in my program.
Thanks!!