0
votes

I try to write a simple chat software. But I am new socket programming and therefore I have a question:

When a chat client sends "goodby" to the server the server should close the client's connection and release all ressources. But after I close the socket the "isConnected()" flag still shows "true".

I have found some threads with similar questions but I must admit that I don't understood all the explainations there.

But is seems that socket.isConnected() does not show the current connection state of a a socket ?

Is this right?

So how can the server close a client connection (socket) and release all ressources etc. back to the operating system?

I want to avoid that over time the server will keep "dead" connections\sockets.

Is it enough to just execute "socket.close" ?

My Server code:

class connection extends Thread
{
        public  Socket           client;
        public  PrintStream      output;    
        private BufferedReader   input;    

...
...

while(true)         //loop where server waits for client's message
{

    //****** wait for client's message
    line=input.readLine();

    //******* Client wants to leave chat  - so close its connection , release server ressources, close this thread...
    if (line.equals("goodbye"))    
        {
            //close I/O streams
            this.input.close();
            this.output.flush();
            this.output.close();  

            //Close Socket
            client.close();     //<-- results in: .isClosed()==true  but : .isConnected()==true

            //close thread (not clear if neccessary)
            this.stop(); 

            //exit loop / this should also exit and thus close this thread
            break;
    }
}
2
Hint: In Java class names start with a capital letter. Call it Connection. - user1907906
@Tichodroma Strictly speaking, they don't have to. - user253751
I would break out of the while loop when you get goodbye then close the socket there. As EJP says below you only need to close the IO Stream and it will close the socket. Also put the close into a finally {} clause so it doesn't get missed. - David George

2 Answers

2
votes

According to Java Docs

public boolean isConnected()

Returns the connection state of the socket.

Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfuly connected prior to being closed.

1
votes

Is it enough to just execute "socket.close" ?

Yes. Normally however you will close the outermost OutputStream or Writer you have wrapped around the socket output stream. That will flush it, close the stream, close the input stream, and close the socket.