1

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!!

Amit Cohen
  • 13
  • 5
  • What do you mean by terminate the program? Do you somehow exit from that while-loop? Do you send a TERM signal from the OS? – dan.m was user2321368 Apr 24 '19 at 17:19
  • 2
    `try { ... } finally { socket.close(); }` (ignoring Exceptions for brevity ....) – user85421 Apr 24 '19 at 17:33
  • I edited the post. By terminate I mean terminate manually or by exception. – Amit Cohen Apr 24 '19 at 17:47
  • I really doubt that there will be any open socket after the program (really) stops. How do you run the `Runnable` ? Probably you should read about [Thread.setDaemon(boolean)](https://stackoverflow.com/questions/28110833/end-java-threads-after-a-while-statement-has-been-run). – PeterMmm Apr 24 '19 at 18:06
  • I don't know if the socket is still actually running, or just isn't closed properly. What I know for sure is that when I use a Python client and it's closed, the server recognizes the disconnection, and in my case it doesn't. In addition, when I manually close the socket within my program, it works and the server recognizes the disconnection. – Amit Cohen Apr 25 '19 at 07:13

0 Answers0